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
|
---|---|---|---|---|---|---|---|---|
Stochastic MACD - Slow and Fast | https://www.tradingview.com/script/n7GPh7c9/ | DOC-STRATEGY | https://www.tradingview.com/u/DOC-STRATEGY/ | 149 | 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='Stochastic MACD - Slow and Fast', shorttitle='Stochastic MACD - Slow and Fast 𓂀', precision=4, timeframe='')
DOC_Strategy = "SLOW - STOCHASTIC MACD"
DOC_Strategy_II = "FAST - STOCHASTIC MACD"
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.wma(2 * ta.wma(source, length / 2) - ta.wma(source, length), math.floor(math.sqrt(length))) :
na
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Data Entry to Build the MACD Slow Stochastic
fastLength = input.int(12 , "Fast Length °°°° ", inline="MSS #1", minval=1, group=DOC_Strategy)
ma1_type = input.string("EMA" , " " , inline="MSS #1", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "HMA"], group=DOC_Strategy)
ma1_source = input.source(close , " " , inline="MSS #1", group=DOC_Strategy)
slowLength = input.int(26 , "Slow Length °°°° " , inline="MSS #1", minval=1, group=DOC_Strategy)
ma2_type = input.string("EMA" , " " , inline="MSS #1", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "HMA"], group=DOC_Strategy)
ma2_source = input.source(close , " " , inline="MSS #1", group=DOC_Strategy)
signalLength = input.int( 9 , "Signal Length °°°" , inline="MSS #1", minval=1, group=DOC_Strategy)
ma3_type = input.string("EMA" , " " , inline="MSS #1", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "HMA"], group=DOC_Strategy)
lookback = input.int(45 , "Look Back " , minval=1, group=DOC_Strategy)
colorLookback = input.int( 2 , "Color Look Back" , minval=0, group=DOC_Strategy)
Color_SSM = input.color (color.rgb(13, 255, 0), "Slow Line Color - Stochastic MACD" , group=DOC_Strategy)
ColorSSSM = input.color (color.rgb(255, 242, 0), "Fast Signal Line Color - Stochastic MACD" , group=DOC_Strategy)
//Data Entry to Build the MACD Slow Stochastic Histogram
hist_color0 = input.color(color.new(#22ff00, 20), 'Positive Rising', group='Slow Histogram - Stochastic MACD') // positive rising
hist_color1 = input.color(color.new(#2ff7f7, 30), 'Positive Falling', group='Slow Histogram - Stochastic MACD') // positive falling
hist_color2 = input.color(color.new(#f82e71, 30), 'Negative Falling', group='Slow Histogram - Stochastic MACD') // negative falling
hist_color3 = input.color(color.new(#ff0000, 20), 'Negative Rising', group='Slow Histogram - Stochastic MACD') // negative rising
//--------------------------------------------------------------------------------------------------------------------------------------------------------------------
//Data Entry to Build the MACD Fast Stochastic
fastLengthXD = input.int( 6 , "Fast Length °°°° ", inline="MFS #2", minval=1, group=DOC_Strategy_II)
ma1_typeXD = input.string("SMA" , " " , inline="MFS #2", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "HMA"], group=DOC_Strategy_II)
ma1_sourceXD = input.source(close , " " , inline="MFS #2", group=DOC_Strategy_II)
slowLengthXD = input.int(12 , "Slow Length °°°° " , inline="MFS #2", minval=1, group=DOC_Strategy_II)
ma2_typeXD = input.string("SMA" , " " , inline="MFS #2", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "HMA"], group=DOC_Strategy_II)
ma2_sourceXD = input.source(close , " " , inline="MFS #2", group=DOC_Strategy_II)
signalLengthXD = input.int( 3 , "Signal Length °°°" , inline="MFS #2", minval=1, group=DOC_Strategy_II)
ma3_typeXD = input.string("SMA" , " " , inline="MFS #2", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "HMA"], group=DOC_Strategy_II)
lookbackXD = input.int(22 , "Look Back " , minval=1, group=DOC_Strategy_II)
colorLookbackXD = input.int( 2 , "Color Look Back" , minval=0, group=DOC_Strategy_II)
Color_FSM = input.color (color.rgb(0, 13, 255), "Fast Line Color - Stochastic MACD" , group=DOC_Strategy_II)
ColorSFSM = input.color (color.rgb(255, 162, 0), "Fast Signal Line Color - Stochastic MACD" , group=DOC_Strategy_II)
//Data Entry to Build the MACD Fast Stochastic Histogram
hist_color0XD = input.color(color.new(#2f3be9, 37), 'Positive Rising', group='Fast Histogram - Stochastic MACD') // positive rising
hist_color1XD = input.color(color.new(#000000, 74), 'Positive Falling', group='Fast Histogram - Stochastic MACD') // positive falling
hist_color2XD = input.color(color.new(#000000, 74), 'Negative Falling', group='Fast Histogram - Stochastic MACD') // negative falling
hist_color3XD = input.color(color.new(#2f3be9, 37), 'Negative Rising', group='Fast Histogram - Stochastic MACD') // negative rising
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Configurable Fast and Slow Parameters to Calculate Slow MACD Stochastic/////////////////////////////
fastMA = ma(ma1_source, fastLength, ma1_type)
slowMA = ma(ma2_source, slowLength, ma2_type)
fastAndSlow = array.from(fastMA, slowMA)
fastAndSlowMax = array.max(fastAndSlow)
fastAndSlowMin = array.min(fastAndSlow)
sFastMA = ta.stoch(fastMA, high, low, lookback)
sSlowMA = ta.stoch(slowMA, high, low, lookback)
//Parameters to Calculate the MACD Slow Stochastic Line and the MACD Slow Stochastic Signal Line//////
smacd = sFastMA - sSlowMA
ssignal = ma(smacd, signalLength, ma3_type)
//Parameters to Calculate the Slow MACD Stochastic Histogram//////////////////////////////////////////
hist = smacd - ssignal
is_rising = ta.rising(hist, colorLookback)
is_falling = ta.falling(hist, colorLookback)
histColor = colorLookback == 0 ? hist > 0 ? hist_color0 : hist_color3 : hist > 0 ? is_rising ? hist_color0 : hist_color1 : is_falling ? hist_color3 : hist_color2
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Configurable Fast and Slow Parameters to Calculate Fast MACD Stochastic/////////////////////////////
fastMAXD = ma(ma1_sourceXD, fastLengthXD, ma1_typeXD)
slowMAXD = ma(ma2_sourceXD, slowLengthXD, ma2_typeXD)
fastAndSlowXD = array.from(fastMAXD, slowMAXD)
fastAndSlowMaxXD = array.max(fastAndSlowXD)
fastAndSlowMinXD = array.min(fastAndSlowXD)
sFastMAXD = ta.stoch(fastMAXD, high, low, lookbackXD)
sSlowMAXD = ta.stoch(slowMAXD, high, low, lookbackXD)
//Parameters to Calculate the MACD Fast Stochastic Line and the MACD Fast Stochastic Signal Line//////
smacdXD = sFastMAXD - sSlowMAXD
ssignalXD = ma(smacdXD, signalLengthXD, ma3_typeXD)
//Parameters to Calculate the Fast MACD Stochastic Histogram//////////////////////////////////////////
histXD = smacdXD - ssignalXD
is_risingXD = ta.rising(histXD, colorLookbackXD)
is_fallingXD = ta.falling(histXD, colorLookbackXD)
histColorXD = colorLookbackXD == 0 ? histXD > 0 ? hist_color0XD : hist_color3XD : histXD > 0 ? is_risingXD ? hist_color0XD : hist_color1XD : is_fallingXD ? hist_color3XD : hist_color2XD
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Period to calculate main line value
Calculation_Period_For_Line = input.int(defval=10, title='Period to calculate the Trend Line', minval=1, group='Trend Line')
Line_ColorLB = input.color (color.rgb(15, 200, 139), "Long/Buy" , group='Trend Line')
Line_ColorSS = input.color (color.rgb(202, 15, 121), "Short/Sell" , group='Trend Line')
//Function to calculate line value////////////////////////////////////////////////////////////////////////////////////////////
Calculate_Line(Period) =>
float highS = ta.highest(Period)
float lowS = ta.lowest(Period)
int trend = 0
trend := close > high[1] ? 1 : close < low[1] ? -1 : nz(trend[1])
trend
//Function to draw line on chart//////////////////////////////////////////////////////////////////////////////////////////////
Draw_Line(Period, Main_Trend) =>
float highS = ta.highest(Period)
float lowS = ta.lowest(Period)
int trend = 0
trend := close > high[1] ? 1 : close < low[1] ? -1 : nz(trend[1])
Main_Trend == 1 ? trend == 1 ? Line_ColorLB : Line_ColorLB : Main_Trend == -1 ? trend == -1 ? Line_ColorSS : Line_ColorSS : na
//Calculate main line value///////////////////////////////////////////////////////////////////////////////////////////////////
Main_Trend = Calculate_Line(Calculation_Period_For_Line)
//Plot Line Zero//////////////////////////////////////////////////////////////////////////////////////////////////////////////
plot( 20, color=Draw_Line(Calculation_Period_For_Line - 9, Main_Trend), title="Upper Trend Line 𓂀", style=plot.style_stepline, histbase= 20, linewidth=2)
plot( 0, color=Draw_Line(Calculation_Period_For_Line - 9, Main_Trend), title="Zero Trend Line 𓂀", style=plot.style_stepline, histbase= 0, linewidth=2)
plot( -20, color=Draw_Line(Calculation_Period_For_Line - 9, Main_Trend), title="Bottom Trend Line 𓂀", style=plot.style_stepline, histbase= -20, linewidth=2)
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Histogram Plot, Fast and Slow MACD Stochastic//////////////////////////////////////////////////////
//Fast////////////////////////////////////////////////////
plot(histXD, style=plot.style_columns, color=histColorXD)
//Slow////////////////////////////////////////////////////
plot(hist, style=plot.style_columns, color=histColor)
//////////////////////////////////////////////////////////
//Plot of the Fast and Slow MACD Stochastic Lines////////////////////////////////////////////////////
//Stochastic MACD Fast////////////////////////////////////
plot(smacdXD, 'Fast Line - Stochastic MACD', color=Color_FSM, linewidth=2)
plot(ssignalXD, 'Fast Signal Line - Stochastic MACD', color=ColorSFSM, linewidth=2)
//Stochastic MACD Slow////////////////////////////////////
plot(smacd, 'Slow Line - Stochastic MACD', color=Color_SSM, linewidth=2)
plot(ssignal, 'Slow Signal Line - Stochastic MACD', color=ColorSSSM, linewidth=2)
//Horizontal Line Graph//////////////////////////////////////////////////////////////////////////////
hline( 15, 'Overbought Line', color=color.rgb(243, 47, 12, 64))
hline(-15, 'Oversold Line', color=color.rgb(9, 233, 24, 70))
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Activate Signals: Long/Buy or Short/Sell///////////////////////////////////////////////////////////////////////////////
Signal_1 = input(false, 'Crossing Slow Lines - Stochastic MACD with Stochastic MACD Signal Line ↑/↓', group='Signal: Long/Buy or Short/Sell')
Signal_2 = input(false, 'Crossing - Fast Line MACD Stochastic with Slow Line MACD Stochastic ▲/▼', group='Signal: Long/Buy or Short/Sell')
//Cross in Long/Buy or Short/Sell////////////////////////////////////////////////////////////////////////////////////////
LB1 = ta.crossover (smacd, ssignal) // Crossing Slow Lines - Stochastic MACD with Stochastic MACD Signal Line
SS1 = ta.crossunder(smacd, ssignal) // Crossing Slow Lines - Stochastic MACD with Stochastic MACD Signal Line
LB2 = ta.crossover (smacdXD, smacd) // Crossing - Fast Line MACD Stochastic with Slow Line MACD Stochastic
SS2 = ta.crossunder(smacdXD, smacd) // Crossing - Fast Line MACD Stochastic with Slow Line MACD Stochastic
//Alert Condition///////////////////////////////////////////////////////////////////////////////////////////////////////
alertcondition((LB1) , 'Slow-Sto.MACD/Slow-Sto.MACD.Signal: Long/Buy', 'Slow-Sto.MACD/Slow-Sto.MACD.Signal: Long/Buy')
alertcondition((SS1) , 'Slow-Sto.MACD/Slow-Sto.MACD.Signal: Short/Sell', 'Slow-Sto.MACD/Slow-Sto.MACD.Signal: Short/Sell')
alertcondition((LB1) or (SS1), 'Slow-Sto.MACD/Slow-Sto.MACD.Signal: Long/Buy or Short/Sell', 'Slow-Sto.MACD/Slow-Sto.MACD.Signal: Long/Buy or Short/Sell')
alertcondition((LB2) , 'Fast-Sto.MACD/Slow-Sto.MACD: Long/Buy', 'Fast-Sto.MACD/Slow-Sto.MACD: Long/Buy')
alertcondition((SS2) , 'Fast-Sto.MACD/Slow-Sto.MACD: Short/Sell', 'Fast-Sto.MACD/Slow-Sto.MACD: Short/Sell')
alertcondition((LB2) or (SS2), 'Fast-Sto.MACD/Slow-Sto.MACD: Long/Buy or Short/Sell', 'Fast-Sto.MACD/Slow-Sto.MACD: Long/Buy or Short/Sell')
alertcondition((LB1) or (SS1) or (LB2) or (SS2), 'Crosses Totals: Long/Buy or Short/Sell', 'Slow-Sto.MACD/Slow-Sto.MACD.Signal or Fast-Sto.MACD/Slow-Sto.MACD: Long/Buy or Short/Sell')
//Signal Condition//////////////////////////////////////////////////////////////////////////////////////////////////////
plotshape(Signal_1 and (LB1) , title='Slow-Sto.MACD/Slow-Sto.MACD.Signal: Long/Buy', text='↑', textcolor=color.new(#FFFFFF, 0), style=shape.labelup, size=size.small, location=location.bottom, color=color.new(#0ebb9e, 0))
plotshape(Signal_1 and (SS1) , title='Slow-Sto.MACD/Slow-Sto.MACD.Signal: Short/Sell', text='↓', textcolor=color.new(#FFFFFF, 0), style=shape.labeldown, size=size.small, location=location.top, color=color.new(#cd0a68, 0))
plotshape(Signal_2 and (LB2) , title='Fast-Sto.MACD/Slow-Sto.MACD: Long/Buy', text='▲', textcolor=color.new(#FFFFFF, 0), style=shape.labelup, size=size.tiny, location=location.bottom, color=color.new(#0ebb9e, 0))
plotshape(Signal_2 and (SS2) , title='Fast-Sto.MACD/Slow-Sto.MACD: Short/Sell', text='▼', textcolor=color.new(#FFFFFF, 0), style=shape.labeldown, size=size.tiny, location=location.top, color=color.new(#cd0a68, 0))
//The End///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// |
RAhul RAJ Out of Range Trade Indicator | https://www.tradingview.com/script/tP7Yid8a-RAhul-RAJ-Out-of-Range-Trade-Indicator/ | HomeZone | https://www.tradingview.com/u/HomeZone/ | 10 | 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/
// © DigitalNivesh
//@version=4
study("RAhul RAJ Out of Range Trade Indicator")
averagePeriod = input(30,"Average Period Range")
highValue = security(syminfo.tickerid, 'D',high)
lowValue = security(syminfo.tickerid, 'D',low)
openValue = security(syminfo.tickerid, 'D',open)
closeValue = security(syminfo.tickerid, 'D',close)
maxAvg = avg((highValue-lowValue),averagePeriod)
minAvg = avg(abs(closeValue-openValue),averagePeriod)
delta = maxAvg-minAvg
plot(maxAvg,color=color.red)
plot(minAvg,color=color.green)
fib = input(1.782,"FIB VALUE")
plot(maxAvg+delta*fib,color=color.blue)
plot(minAvg-delta*fib,color=color.blue)
is_newbar(res) =>
t = time(res, "0915-1530")
not na(t) and (na(t[1]) or t > t[1])
open_range = valuewhen(is_newbar('D'), open, 0)
openVal = security(syminfo.tickerid, '5', open_range)
plot(abs(open_range-close),color=color.yellow)
|
Bollinger Band Alert with RSI Filter Indicator | https://www.tradingview.com/script/eWceE4Lq-Bollinger-Band-Alert-with-RSI-Filter-Indicator/ | dwdventer | https://www.tradingview.com/u/dwdventer/ | 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/
// © dwdventer
//@version=5
indicator('Bollinger Band Alert with RSI Filter', shorttitle="BBRSI+ALERT INDICATOR", overlay=true)
// Inputs
length = input(title='BB Length', defval=20)
mult = input.float(title='BB Multiplier', defval=2, step=0.1)
upper_rsi = input(title='Upper RSI', defval=75)
lower_rsi = input(title='Lower RSI', defval=25)
rsi_length = input(title='RSI Length', defval=14)
// Bollinger Bands
bb_avg = ta.sma(close, length)
bb_upper = bb_avg + mult * ta.stdev(close, length)
bb_lower = bb_avg - mult * ta.stdev(close, length)
// RSI
rsi = ta.rsi(close, rsi_length)
// Plotting
plot(bb_upper, color=color.new(color.red, 0), linewidth=1)
plot(bb_lower, color=color.new(color.red, 0), linewidth=1)
plot(bb_avg, color=color.new(color.blue, 0), linewidth=1)
// Long and Short Entry Overlays
long_entry = close < bb_lower
short_entry = close > bb_upper
plotshape(long_entry and rsi < lower_rsi, style=shape.triangleup, location=location.belowbar, color=color.new(color.green, 0), size=size.small, title='Long Entry')
plotshape(short_entry and rsi > upper_rsi, style=shape.triangledown, location=location.abovebar, color=color.new(color.red, 0), size=size.small, title='Short Entry')
// Alert conditions for long and short entries
alertcondition(long_entry and rsi < lower_rsi, title='Long Entry', message='Long Entry Alert')
alertcondition(short_entry and rsi > upper_rsi, title='Short Entry', message='Short Entry Alert') |
Transmit signals to overlay | https://www.tradingview.com/script/MEy5qnzv-Transmit-signals-to-overlay/ | x7-am | https://www.tradingview.com/u/x7-am/ | 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/
// © x7-am
//@version=5
// This indicator transmit signals from another indicator panel to the main panel over the chart, when it is not possible to use the main one with the "overlay=true" attribute.
indicator("Transmit signals", timeframe='', overlay=true)
data = input.source(close, 'Source', 'Select the source of the input data') // input data signal must be '1' to BUY, and '0' to SELL
plotshape(data==1, title='BUY', style=shape.triangleup, color=color.green, location=location.belowbar, size=size.tiny, display=display.pane)
plotshape(data==0, title='SELL', style=shape.triangledown, color=color.red, location=location.abovebar, size=size.tiny, display=display.pane)
bgcolor(data==1 ? #1c942085 : data==0 ? #ae272787 : na, display=display.all)
//--------------------------------
//---- Signals to Alert ----
plot(data, title='BUYSELL',display=display.none,editable=false) // This hidden plot for BUY and SELL alert in one message
alertcondition(data==1 or data==0, title='Alert BUY & SELL', message='BUY(1) or SELL(0): {{plot("BUYSELL")}}') // BUY and SELL alert in one message, 1 = BUY and 0 = SELL
// One alert in BUY and second alert to SELL message
alertcondition(data==1, title='Alert BUY', message='BUY')
alertcondition(data==0, title='Alert SELL', message='SELL') |
Global Unemployment Rate | https://www.tradingview.com/script/Njsidi4C-Global-Unemployment-Rate/ | miguefinance | https://www.tradingview.com/u/miguefinance/ | 5 | 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/
// © miguefinance
// The Global Unemployment rate includes the Eurozone + 19 countries from all the continents, which are some of the richest countries as well as some of the most populous
// it does not include India as its unemployment data as of today is only since year 2019
//@version=5
indicator("Global Unemployment Rate", overlay=false)
// PINE SCRIPTS LIMITS TO REQUESTING 40 SECURITIES, SO I HAD TO PUT ONLY SOME THE RICHEST COUNTRIES AND THE MOST POPULOUS
EUPOP=request.security("ECONOMICS:EUPOP", timeframe.period, close)
EUUR=request.security("ECONOMICS:EUUR", timeframe.period, close)
//north america
USPOP=request.security("ECONOMICS:USPOP", timeframe.period, close)
USUR=request.security("ECONOMICS:USUR", timeframe.period, close)
//CAPOP=request.security("ECONOMICS:CAPOP", timeframe.period, close)
//CAUR=request.security("ECONOMICS:CAUR" , timeframe.period, close)
// non EU europe
//CHPOP=request.security("ECONOMICS:CHPOP", timeframe.period, close)
//CHUR=request.security("ECONOMICS:CHUR", timeframe.period, close)
GBPOP=request.security("ECONOMICS:GBPOP", timeframe.period, close)
GBUR=request.security("ECONOMICS:GBUR", timeframe.period, close)
//FIPOP=request.security("ECONOMICS:FIPOP", timeframe.period, close)
//FIUR=request.security("ECONOMICS:FIUR", timeframe.period, close)
//SEPOP=request.security("ECONOMICS:SEPOP", timeframe.period, close)
//SEUR=request.security("ECONOMICS:SEUR", timeframe.period, close)
RUPOP=request.security("ECONOMICS:RUPOP", timeframe.period, close)
RUUR=request.security("ECONOMICS:RUUR", timeframe.period, close)
//pacific
AUPOP=request.security("ECONOMICS:AUPOP", timeframe.period, close)
AUUR=request.security("ECONOMICS:AUUR", timeframe.period, close) // australia data is from 1979
//NZPOP=request.security("ECONOMICS:NZPOP", timeframe.period, close)
//NZUR=request.security("ECONOMICS:NZUR", timeframe.period, close)
//Asia
BDPOP=request.security("ECONOMICS:BDPOP", timeframe.period, close)
BDUR=request.security("ECONOMICS:BDUR", timeframe.period, close) ///bangladesh data is from 1992
CNPOP=request.security("ECONOMICS:CNPOP", timeframe.period, close)
CNUR=request.security("ECONOMICS:CNUR", timeframe.period, close) // China data is from 2002
IDPOP=request.security("ECONOMICS:IDPOP", timeframe.period, close)
IDUR=request.security("ECONOMICS:IDUR", timeframe.period, close) //indonesia data is from 1983
//INPOP=request.security("ECONOMICS:INPOP", timeframe.period, close)
//INUR=request.security("ECONOMICS:INUR", timeframe.period, close) //india DATA IS FROM 2019 ONLY!!! so have to disable it
JPPOP=request.security("ECONOMICS:JPPOP", timeframe.period, close)
JPUR=request.security("ECONOMICS:JPUR", timeframe.period, close) // japan data is from 1954
//KRPOP=request.security("ECONOMICS:KRPOP", timeframe.period, close)
//KRUR=request.security("ECONOMICS:KRUR", timeframe.period, close) //Korea data is from 2008 only!
MMPOP=request.security("ECONOMICS:MMPOP", timeframe.period, close)
MMUR=request.security("ECONOMICS:MMUR", timeframe.period, close) // mianmar data is from 1991
PHPOP=request.security("ECONOMICS:PHPOP", timeframe.period, close)
PHUR=request.security("ECONOMICS:PHUR", timeframe.period, close) // philipines data from 1986
PKPOP=request.security("ECONOMICS:PKPOP", timeframe.period, close)
PKUR=request.security("ECONOMICS:PKUR", timeframe.period, close) // pakistan data is from 1986
THPOP=request.security("ECONOMICS:THPOP", timeframe.period, close)
THUR=request.security("ECONOMICS:THUR", timeframe.period, close) // thailand data is from 1978
VNPOP=request.security("ECONOMICS:VNPOP", timeframe.period, close)
VNUR=request.security("ECONOMICS:VNUR", timeframe.period, close) // vietnam data is from 1999
//SGPOP=request.security("ECONOMICS:SGPOP", timeframe.period, close)
//SGUR=request.security("ECONOMICS:SGUR", timeframe.period, close)
//latin america
ARPOP=request.security("ECONOMICS:ARPOP", timeframe.period, close)
ARUR=request.security("ECONOMICS:ARUR", timeframe.period, close) //argetina data is from 2003
//BRPOP=request.security("ECONOMICS:BRPOP", timeframe.period, close)
//BRUR=request.security("ECONOMICS:BRUR", timeframe.period, close) // data is from 2012 ONLY.. this is the FILTER
//CLPOP=request.security("ECONOMICS:CLPOP", timeframe.period, close)
//CLUR=request.security("ECONOMICS:CLUR", timeframe.period, close)
//COPOPv=request.security("ECONOMICS:COPOP", timeframe.period, close)
//COUR=request.security("ECONOMICS:COUR", timeframe.period, close)
MXPOP=request.security("ECONOMICS:MXPOP", timeframe.period, close)
MXUR=request.security("ECONOMICS:MXUR", timeframe.period, close) //mexico data is from 1995
//PEPOP=request.security("ECONOMICS:PEPOP", timeframe.period, close)
//PEUR=request.security("ECONOMICS:PEUR", timeframe.period, close)
//VEPOP=request.security("ECONOMICS:VEPOP", timeframe.period, close)
//VEUR=request.security("ECONOMICS:VEUR", timeframe.period, close)
//middle east
//AEPOP=request.security("ECONOMICS:AEPOP", timeframe.period, close)
//AEUR=request.security("ECONOMICS:AEUR", timeframe.period, close)
//ILPOP=request.security("ECONOMICS:ILPOP", timeframe.period, close)
//ILUR=request.security("ECONOMICS:ILUR", timeframe.period, close)
//TRPOP=request.security("ECONOMICS:TRPOP", timeframe.period, close)
//TRUR=request.security("ECONOMICS:TRUR", timeframe.period, close) // turkey data is from 2005
//IRPOP=request.security("ECONOMICS:IRPOP", timeframe.period, close)
//IRUR=request.security("ECONOMICS:IRUR", timeframe.period, close)
//africa
CDPOP=request.security("ECONOMICS:CDPOP", timeframe.period, close)
CDUR=request.security("ECONOMICS:CDUR", timeframe.period, close) // congo data is from 2000
EGPOP=request.security("ECONOMICS:EGPOP", timeframe.period, close)
EGUR=request.security("ECONOMICS:EGUR", timeframe.period, close) // egypt data from 1994
ETPOP=request.security("ECONOMICS:ETPOP", timeframe.period, close)
ETUR=request.security("ECONOMICS:ETUR", timeframe.period, close) //ethiopia data from 1999
//KEPOP=request.security("ECONOMICS:KEPOP", timeframe.period, close)
//KEUR=request.security("ECONOMICS:KEUR", timeframe.period, close) //Kenya data from 1992
//NGPOP=request.security("ECONOMICS:NGPOP", timeframe.period, close)
//NGUR=request.security("ECONOMICS:NGUR", timeframe.period, close) //data is only from 2006
//TZPOP=request.security("ECONOMICS:TZPOP", timeframe.period, close)
//TZUR=request.security("ECONOMICS:TZUR", timeframe.period, close) //data since 2001
ZAPOP=request.security("ECONOMICS:ZAPOP", timeframe.period, close)
ZAUR=request.security("ECONOMICS:ZAUR", timeframe.period, close) // data is from year 2000
// Normalize the unemployment data
// 40 COUNTRIES (it fails due to TradingView Limits):
//total_population = EUPOP + EUUR + USPOP + USUR + CAPOP + CAUR + CHPOP + CHUR + GBPOP + GBUR + FIPOP + FIUR + SEPOP + SEUR + RUPOP + RUUR + AUPOP + AUUR + NZPOP + NZUR + BDPOP + BDUR + CNPOP + CNUR + IDPOP + IDUR + INPOP + INUR + JPPOP + JPUR + KRPOP + KRUR + MMPOP + MMUR + PHPOP + PHUR + PKPOP + PKUR + THPOP + THUR + VNPOP + VNUR + SGPOP + SGUR + ARPOP + ARUR + BRPOP + BRUR + CLPOP + CLUR + COPOPv + COUR + MXPOP + MXUR + PEPOP + PEUR + VEPOP + VEUR + AEPOP + AEUR + ILPOP + ILUR + TRPOP + TRUR + IRPOP + IRUR + CDPOP + CDUR + EGPOP + EGUR + ETPOP + ETUR + KEPOP + KEUR + NGPOP + NGUR + TZPOP + TZUR + ZAPOP + ZAUR
//total_unemployed_population = EUPOP * EUUR + USPOP * USUR + CAPOP * CAUR + CHPOP * CHUR + GBPOP * GBUR + FIPOP * FIUR + SEPOP * SEUR + RUPOP * RUUR + AUPOP * AUUR + NZPOP * NZUR + BDPOP * BDUR + CNPOP * CNUR + IDPOP * IDUR + INPOP * INUR + JPPOP * JPUR + KRPOP * KRUR + MMPOP * MMUR + PHPOP * PHUR + PKPOP * PKUR + THPOP * THUR + VNPOP * VNUR + SGPOP * SGUR + ARPOP * ARUR + BRPOP * BRUR + CLPOP * CLUR + COPOPv * COUR + MXPOP * MXUR + PEPOP * PEUR + VEPOP * VEUR + AEPOP * AEUR + ILPOP * ILUR + TRPOP * TRUR + IRPOP * IRUR + CDPOP * CDUR + EGPOP * EGUR + ETPOP * ETUR + KEPOP * KEUR + NGPOP * NGUR + TZPOP * TZUR + ZAPOP * ZAUR
// 20 COUNTRIES (most important in population and some of most rich), but some of the have very short data:
//total_population = EUPOP+ USPOP + RUPOP + BDPOP + CNPOP + IDPOP + JPPOP + KRPOP + MMPOP + PKPOP + VNPOP + ARPOP + BRPOP + MXPOP + TRPOP + CDPOP + EGPOP + ZAPOP
//total_unemployed_population = (EUPOP*EUUR + USPOP*USUR + RUPOP*RUUR + BDPOP*BDUR + CNPOP*CNUR + IDPOP*IDUR + JPPOP*JPUR + KRPOP*KRUR + MMPOP*MMUR + PKPOP*PKUR + VNPOP*VNUR + ARPOP*ARUR + BRPOP*BRUR + MXPOP*MXUR + TRPOP*TRUR + CDPOP*CDUR + EGPOP*EGUR + ZAPOP*ZAUR)
// 20 countries longer data in trading view (korea, brazil, turkey were removed due to short data, then added instead TH, GB, ET, PH ):
// I have chosen countries with data from at least year 2002 (which is oldest data of China, to not ignore both china and india) so can be seen effect of the two last market crashes
total_population = EUPOP+ USPOP +GBPOP + RUPOP + AUPOP + BDPOP + CNPOP + IDPOP + JPPOP + MMPOP + PKPOP + PHPOP + THPOP + VNPOP + ARPOP + MXPOP + CDPOP + EGPOP + ETPOP + ZAPOP
total_unemployed_population = (EUPOP*EUUR + USPOP*USUR + GBPOP*GBUR + RUPOP*RUUR+ AUPOP*AUUR + BDPOP*BDUR + CNPOP*CNUR + IDPOP*IDUR + JPPOP*JPUR + MMPOP*MMUR + PKPOP*PKUR + PHPOP*PHUR+ THPOP*THUR +VNPOP*VNUR + ARPOP*ARUR + MXPOP*MXUR + CDPOP*CDUR + EGPOP*EGUR + ETPOP*ETUR + ZAPOP*ZAUR)
global_ur_normalized = total_unemployed_population / total_population
plot(global_ur_normalized, color=color.blue, title="Global Unemplyment Rate", linewidth=2)
|
30 Second Futures Session Open Range | https://www.tradingview.com/script/EsYTQkl0-30-Second-Futures-Session-Open-Range/ | SamRecio | https://www.tradingview.com/u/SamRecio/ | 269 | 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
//Insipired by Tradingview User @Emmonspired
//@version=5
indicator("30 Second Futures Session Open Range",shorttitle = "30 Sec OR", overlay = true, max_lines_count = 500)
or_time = hour(time,"America/Chicago") + minute(time,"America/Chicago")*0.01
l_high = request.security_lower_tf(syminfo.tickerid,"30S",high)
l_low = request.security_lower_tf(syminfo.tickerid,"30S",low)
get_or(_time) =>
hi = ta.valuewhen(or_time == _time and second == 0,array.size(l_high)>0?array.get(l_high,0):0,0)
lo = ta.valuewhen(or_time == _time and second == 0,array.size(l_low)>0?array.get(l_low,0):0,0)
[hi,lo]
asn = 17.00
eur = 2.00
ny = 8.30
[asn_h,asn_l] = get_or(asn)
[eur_h,eur_l] = get_or(eur)
[ny_h,ny_l] = get_or(ny)
asn_m = math.avg(asn_h,asn_l)
eur_m = math.avg(eur_h,eur_l)
ny_m = math.avg(ny_h,ny_l)
plot(ny_h, color = color.aqua, title = "RTH OR High", display = display.pane+display.price_scale, style = plot.style_stepline)
plot(ny_m, color = color.yellow, title = "RTH OR Mid", linewidth = 2, display = display.pane+display.price_scale, style = plot.style_stepline)
plot(ny_l, color = color.aqua, title = "RTH OR Low", display = display.pane+display.price_scale, style = plot.style_stepline)
plot(asn_h, color = color.orange, title = "Globex OR High", display = display.pane+display.price_scale, style = plot.style_stepline)
plot(asn_m, color = color.fuchsia, title = "Globex OR Mid", linewidth = 2, display = display.pane+display.price_scale, style = plot.style_stepline)
plot(asn_l, color = color.orange, title = "Globex OR Low", display = display.pane+display.price_scale, style = plot.style_stepline)
plot(eur_h, color = color.olive, title = "Europe OR High", display = display.pane+display.price_scale, style = plot.style_stepline)
plot(eur_m, color = color.lime, title = "Europe OR Mid", linewidth = 2, display = display.pane+display.price_scale, style = plot.style_stepline)
plot(eur_l, color = color.olive, title = "Europe OR Low", display = display.pane+display.price_scale, style = plot.style_stepline)
lab(_text,_color,_value) =>
lab = label.new(bar_index+1, _value, style = label.style_label_left,color = color.rgb(0,0,0,100), textcolor = _color, text = str.tostring(_value,"##.00"),tooltip = _text, size = size.small)
label.delete(lab[1])
lab("RTH OR-H",color.aqua,ny_h)
lab("RTH OR-M",color.yellow,ny_m)
lab("RTH OR-L",color.aqua,ny_l)
lab("GLOBEX OR-H",color.orange,asn_h)
lab("GLOBEX OR-M",color.fuchsia,asn_m)
lab("GLOBEX OR-L",color.orange,asn_l)
lab("EUROPE OR-H",color.olive,eur_h)
lab("EUROPE OR-M",color.lime,eur_m)
lab("EUROPE OR-L",color.olive,eur_l)
//Price Targets//
t_tog = input.bool(true, title = "Display RTH Targets", group = "Targets")
t_perc = input.float(50, title = "Target %", group = "Targets", inline = "1")*0.01
t_color = input.color(color.new(color.silver,50), title = "", group = "Targets", inline = "1")
t_style = input.string("- - -", title = "Style", options = ["___","- - -",". . .","none"], group = "Targets", inline = "2")
t_width = input.int(1, minval = 1, title = "Width", group = "Targets", inline = "2")
extend_lines(_linearray) =>
if array.size(_linearray) > 0
for i = 0 to array.size(_linearray) - 1
lx = array.get(_linearray,i)
line.set_x2(lx,bar_index)
linestyle(_input) =>
_input == "___"?line.style_solid:
_input == "- - -"?line.style_dashed:
_input == ". . ."?line.style_dotted:
na
reset = or_time == ny
width = ny_h-ny_l
value = math.max(width*t_perc,syminfo.mintick)
var roof = ny_h
var floor = ny_l
all_lines = line.all
if reset
roof := ny_h
floor := ny_l
if array.size(all_lines) > 0
for i = 0 to array.size(all_lines) - 1
line.delete(array.get(all_lines, i))
if close<floor and t_tog
down_count = math.ceil((floor-close)/value)
for i = 1 to down_count
line.new(bar_index,floor-(i*value),bar_index,floor-(i*value),color = t_color, width = t_width, style = linestyle(t_style))
floor := floor-(down_count*value)
if close>roof and t_tog
up_count = math.ceil((close-roof)/value)
for i = 1 to up_count
line.new(bar_index,roof+(i*value),bar_index,roof+(i*value),color = t_color, width = t_width, style = linestyle(t_style))
roof := roof+(up_count*value)
extend_lines(all_lines)
|
Flare | https://www.tradingview.com/script/5QSO13Ib-Flare/ | fikira | https://www.tradingview.com/u/fikira/ | 857 | study | 5 | MPL-2.0 | fi(ki)=>'ra' // © fikira 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= "Flare", max_lines_count= 500, max_labels_count= 500, overlay= true)
_='
- - - ––––––––––––– - - - [ INPUT ] - - - ––––––––––––– - - - ='
lnSize = input.int (defval= 80 , title= 'Width of flare' , minval= 5, maxval=83)
clBack = math.min (lnSize, input.int(defval= 40, title= 'x bars back (close)', minval= 1, maxval=83,
tooltip = "will take the lowest value of \n ╭╴ 'Width of flare'\n ╰╴ 'x close back' " ))
pow = input.float(defval= 1.2 , title= 'pow' , step = 0.05 )
step = input.float(defval= 0.15 , title= 'step' , step = 0.01 )
iBgc = input.bool (defval= false , title= 'bgcolor' )
sLab = input.bool (defval= true , title= 'Label' ,
tooltip = "Shows start of flare -> point 'x bars back (close)'" )
st_Draw = input.int (defval= 1000 , title= 'start calculating last x bars' )
_='
- - - ––––––––––––– - - - [ create type "flare" ] - - - ––––––––––––– - - - ='
// @type An object of 5 linefill array's (a_Lf1-5), 1 int iDir (direction) & 1 color (cCol)
type flare
linefill[] a_Lf1 = na
linefill[] a_Lf2 = na
linefill[] a_Lf3 = na
linefill[] a_Lf4 = na
linefill[] a_Lf5 = na
int iDir = na
color cCol = na
_='
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
- - - ––––––––––––– - - - [ FUNCTIONS ] - - - ––––––––––––– - - -
- - - ––––––––––––– - - - [ ] - - - ––––––––––––– - - - ='
_='= ––––––––––––––––––––––––––[ add lines to array at bar_index 0 ]–––––––––––––––––––––––––– ='
// @function Sets the new created flare object at the first bar
set_flare_0(flare obj) =>
if barstate.isfirst
//
for i = 0 to lnSize
//
l1 = line.new(x1= na, y1= na, x2= na, y2= na)
l2 = line.new(x1= na, y1= na, x2= na, y2= na)
l3 = line.new(x1= na, y1= na, x2= na, y2= na)
l4 = line.new(x1= na, y1= na, x2= na, y2= na)
l5 = line.new(x1= na, y1= na, x2= na, y2= na)
l6 = line.new(x1= na, y1= na, x2= na, y2= na)
// note *1
obj.a_Lf1.unshift(linefill.new(line1= l1, line2= l2, color= na))
obj.a_Lf2.unshift(linefill.new(line1= l2, line2= l3, color= na))
obj.a_Lf3.unshift(linefill.new(line1= l3, line2= l4, color= na))
obj.a_Lf4.unshift(linefill.new(line1= l4, line2= l5, color= na))
obj.a_Lf5.unshift(linefill.new(line1= l5, line2= l6, color= na))
_='= ––––––––––––––––––––––––––[ set lines x1, y1, x2, y2, this at every bar ]–––––––––––––––––––––––––– ='
// @function Updates every linefill from the flare object
set_flare_A(flare obj, series int closeBack) =>
//
if last_bar_index - bar_index < st_Draw
for i = 0 to lnSize
// note *2
obj.a_Lf1.get(i).get_line1().set_xy1(bar_index - closeBack + i , close[closeBack] - math.pow(i -1, pow + (2 * step)))
obj.a_Lf1.get(i).get_line1().set_xy2(bar_index - closeBack + i + 1, close[closeBack] - math.pow(i , pow + (2 * step)))
//
obj.a_Lf1.get(i).get_line2().set_xy1(bar_index - closeBack + i , close[closeBack] - math.pow(i -1, pow + (1 * step)))
obj.a_Lf1.get(i).get_line2().set_xy2(bar_index - closeBack + i + 1, close[closeBack] - math.pow(i , pow + (1 * step)))
obj.a_Lf2.get(i).get_line1().set_xy1(bar_index - closeBack + i , close[closeBack] - math.pow(i -1, pow + (1 * step)))
obj.a_Lf2.get(i).get_line1().set_xy2(bar_index - closeBack + i + 1, close[closeBack] - math.pow(i , pow + (1 * step)))
//
obj.a_Lf2.get(i).get_line2().set_xy1(bar_index - closeBack + i , close[closeBack] - math.pow(i -1, pow + (0 * step)))
obj.a_Lf2.get(i).get_line2().set_xy2(bar_index - closeBack + i + 1, close[closeBack] - math.pow(i , pow + (0 * step)))
obj.a_Lf3.get(i).get_line1().set_xy1(bar_index - closeBack + i , close[closeBack] - math.pow(i -1, pow + (0 * step)))
obj.a_Lf3.get(i).get_line1().set_xy2(bar_index - closeBack + i + 1, close[closeBack] - math.pow(i , pow + (0 * step)))
//
obj.a_Lf3.get(i).get_line2().set_xy1(bar_index - closeBack + i , close[closeBack] + math.pow(i -1, pow + (0 * step)))
obj.a_Lf3.get(i).get_line2().set_xy2(bar_index - closeBack + i + 1, close[closeBack] + math.pow(i , pow + (0 * step)))
obj.a_Lf4.get(i).get_line1().set_xy1(bar_index - closeBack + i , close[closeBack] + math.pow(i -1, pow + (0 * step)))
obj.a_Lf4.get(i).get_line1().set_xy2(bar_index - closeBack + i + 1, close[closeBack] + math.pow(i , pow + (0 * step)))
//
obj.a_Lf4.get(i).get_line2().set_xy1(bar_index - closeBack + i , close[closeBack] + math.pow(i -1, pow + (1 * step)))
obj.a_Lf4.get(i).get_line2().set_xy2(bar_index - closeBack + i + 1, close[closeBack] + math.pow(i , pow + (1 * step)))
obj.a_Lf5.get(i).get_line1().set_xy1(bar_index - closeBack + i , close[closeBack] + math.pow(i -1, pow + (1 * step)))
obj.a_Lf5.get(i).get_line1().set_xy2(bar_index - closeBack + i + 1, close[closeBack] + math.pow(i , pow + (1 * step)))
//
obj.a_Lf5.get(i).get_line2().set_xy1(bar_index - closeBack + i , close[closeBack] + math.pow(i -1, pow + (2 * step)))
obj.a_Lf5.get(i).get_line2().set_xy2(bar_index - closeBack + i + 1, close[closeBack] + math.pow(i , pow + (2 * step)))
_='= ––––––––––––––––––––––––––[ set color ~ condition, this at every bar ]–––––––––––––––––––––––––– ='
// @function sets color ~ condition at every bar
set_flare_B(flare obj) =>
//
if last_bar_index - bar_index < st_Draw
dist = bar_index - obj.a_Lf1.get(0).get_line1().get_x1()
// note *3
clAbove6 = close > obj.a_Lf5.get(dist).get_line2().get_price(bar_index)
clAbove5 = close > obj.a_Lf4.get(dist).get_line2().get_price(bar_index)
clAbove4 = close > obj.a_Lf3.get(dist).get_line2().get_price(bar_index)
clBelow3 = close < obj.a_Lf3.get(dist).get_line1().get_price(bar_index)
clBelow2 = close < obj.a_Lf2.get(dist).get_line1().get_price(bar_index)
clBelow1 = close < obj.a_Lf1.get(dist).get_line1().get_price(bar_index)
// note *4
obj.iDir :=
switch
clAbove6 => 3
clAbove5 => 2
clAbove4 => 1
clBelow1 => -3
clBelow2 => -2
clBelow3 => -1
=> 0
//
obj.cCol :=
switch
clAbove6 => input.color(defval= color.lime , title= '', group= 'color UP', inline= 'up')
clAbove5 => input.color(defval= color.green , title= '', group= 'color UP', inline= 'up')
clAbove4 => input.color(defval= color.yellow, title= '', group= 'color UP', inline= 'up')
clBelow1 => input.color(defval= #FF0000 , title= '', group= 'color DN', inline= 'dn')
clBelow2 => input.color(defval= color.red , title= '', group= 'color DN', inline= 'dn')
clBelow3 => input.color(defval= color.orange, title= '', group= 'color DN', inline= 'dn')
=> color.blue
//
for i = 0 to lnSize
// note *5
obj.a_Lf1.get(i).get_line1().set_color(color.new(obj.cCol, math.max(0, 100 - (100 / lnSize * i))))
obj.a_Lf2.get(i).get_line1().set_color(color.new(obj.cCol, 100 ))
obj.a_Lf3.get(i).get_line1().set_color(color.new(obj.cCol, math.max(0, 100 - (100 / lnSize * i))))
obj.a_Lf4.get(i).get_line2().set_color(color.new(obj.cCol, 100 ))
obj.a_Lf4.get(i).get_line1().set_color(color.new(obj.cCol, math.max(0, 100 - (100 / lnSize * i))))
obj.a_Lf5.get(i).get_line2().set_color(color.new(obj.cCol, math.max(0, 100 - (100 / lnSize * i))))
// note *6
obj.a_Lf1.get(i).set_color (color.new(obj.cCol, math.max(0, math.min(100 , 100 / lnSize * i))))
obj.a_Lf2.get(i).set_color (color.new(obj.cCol, math.max(0, math.min(100 , 125 / lnSize * i))))
//
obj.a_Lf4.get(i).set_color (color.new(obj.cCol, math.max(0, math.min(100 , 125 / lnSize * i))))
obj.a_Lf5.get(i).set_color (color.new(obj.cCol, math.max(0, math.min(100 , 100 / lnSize * i))))
_='
- - - ––––––––––––– - - - [ ] - - - ––––––––––––– - - -
––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– ='
_='
- - - ––––––––––––– - - - [ ACTION ] - - - ––––––––––––– - - - ='
_='= ––––––––––––––––––––––––––[ Draw "Flare" ]–––––––––––––––––––––––––– ='
var flare ConcaveCone =
flare.new(
a_Lf1= array.new<linefill>(),
a_Lf2= array.new<linefill>(),
a_Lf3= array.new<linefill>(),
a_Lf4= array.new<linefill>(),
a_Lf5= array.new<linefill>(),
iDir= na,
cCol= na)
set_flare_0(ConcaveCone )
set_flare_A(ConcaveCone, clBack )
set_flare_B(ConcaveCone )
_='= ––––––––––––––––––––––––––[ Draw plotshape() & bgcolor ]–––––––––––––––––––––––––– ='
plotshape (ConcaveCone.iDir <= 0 ? high : na, "", shape.labeldown, location.abovebar, color.new(ConcaveCone.cCol, 25), 0, size=size.tiny)
plotshape (ConcaveCone.iDir >= 0 ? low : na, "", shape.labelup , location.belowbar, color.new(ConcaveCone.cCol, 25), 0, size=size.tiny)
bgcolor (iBgc ? color.new(ConcaveCone.cCol, 95) : na )
_='= ––––––––––––––––––––––––––[ Draw start label() ]–––––––––––––––––––––––––– ='
up = close[clBack] > open[clBack]
var label lab = na
if sLab
lab :=
label.new(bar_index - clBack, close[clBack],
text = 'start', textcolor= color.yellow ,
style= up ? label.style_label_lower_right :
label.style_label_upper_right )
(lab[1]).delete()
_='
- - - ––––––––––––– - - - [ NOTES ] - - - ––––––––––––– - - - ='
// note *1
_=' obj.a_Lf1.unshift(linefill.new(l1, l2, na)) in "set_flare_0()" function ='
_=' obj -> object (ConcaveCone) ='
_=' a_Lf1 -> first linefill[] array of flare object ='
_=' In the ACTION part, we create a "ConcaveCone" OBJECT of "flare" TYPE ='
_=' "ConcaveCone" has a "linefill[]" field, here we add a "linefill.new()" ='
_=' -> ConcaveCone.a_Lf1.unshift(linefill.new(...)) ='
// note *2
_=' obj.a_Lf1.get(i).get_line1().set_xy1(bar_index ..., close ...) in "set_flare_A()" function ='
_=' obj -> object (ConcaveCone) ='
_=' a_Lf1 -> first linefill[] array of flare object ='
_=' get(i) -> get linefill in linefill[] array ='
_=' get_line1() -> get_line1() of retrieved linefill ='
_=' set_xy1 -> sets x1 & y1 of retrieved line1() ='
// note *3
_=' obj.a_Lf1.get(dist).get_line2().get_price(bar_index) in "set_flare_B()" function ='
_=' obj -> object (ConcaveCone) ='
_=' a_Lf1 -> first linefill[] array of flare object ='
_=' get(dist) -> dist is 1 specific linefill from the linefill[] array ='
_=' -> in this case the line at currect bar ='
_=' get_line2() -> get_line2() of retrieved linefill ='
_=' get_price() -> retrieves price from this line at current bar_index ='
_=' -> then check where close is against prices (below/above) ='
// note *4
_=' -> update iDir of flare object (obj.iDir) ='
_=' -> update color of flare object (obj.cCol) ='
// note *5
_=' obj.a_Lf1.get(i).get_line1().set_color(color.new(obj.cCol,...)) in "set_flare_B()" function ='
_=' obj -> object (ConcaveCone) ='
_=' a_Lf1 -> first linefill[] array of flare object ='
_=' get(i) -> get linefill in linefill[] array ='
_=' get_line1() -> get_line1() of retrieved linefill ='
_=' set_color() -> sets colour of retrieved line1() ='
_=' another option is to change colour according to "i" and "lnSize" values ='
_=' Examples: ='
_=' obj.a_Lf1.get(i).get_line1().set_color(color.rgb(0, ((255 / lnSize) * i), ((255 / lnSize) * i), 0)) ='
_=' obj.a_Lf1.get(i).get_line1().set_color(color.rgb(200, 255 - ((255 / lnSize) * i), 0, 0) ='
// note *6
_=' obj.a_Lf1.get(i).set_color(color.new(cCol,...)) in "set_flare_B()" function ='
_=' obj -> object (ConcaveCone) ='
_=' a_Lf1 -> first linefill[] array of flare object ='
_=' get(i) -> get linefill in linefill[] array ='
_=' set_color() -> sets colour of retrieved linefill ='
_='
- - - ––––––––––––– - - - [ END ] - - - ––––––––––––– - - - ='
|
Easy RSI by nnam | https://www.tradingview.com/script/HxhBJCtM-Easy-RSI-by-nnam/ | nnamdert | https://www.tradingview.com/u/nnamdert/ | 94 | 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/
// © nnamdert
//@version=5
indicator("Easy RSI by nnam", overlay = true)
//BEGIN GET USER INPUTS=========================================================================================================//
color_bars = input.bool( //
defval = true, //
title ='Color Code Bars?', //
tooltip = 'Selecting this Box will Color Code Bars' //
) //
show_current_price_label = input.bool( //
defval = true, //
title ='Show Current Price on Chart?', //
tooltip = 'Selecting this Box will plot the realtime price on the chart' //
) //
plot_rsi_labels = input.bool( //
defval = true, //
title ='Plot current RSI Value on Chart?', //
tooltip = 'Selecting this Box will plot the current RSI Value on the chart' //
) //
plot_obos_labels = input.bool( //
defval = true, //
title ='Plot RSI Overbought and Oversold Alerts on Chart?', //
tooltip = 'Selecting this Box will plot Realtime RSI Oversold and Overbought condition alerts on the chart' //
) //
rsi_oversold_condition = input.int( //
defval = 15, //
title = 'Set Oversold Condition', //
tooltip = 'Default is usually 30' //
) //
rsi_overbought_condition = input.int( //
defval = 85, //
title = 'Set Overbought Condition', //
tooltip = 'Default is usually 70' //
) //
rsi_Length = input.int( //
defval = 6, //
title = 'RSI Length', //
tooltip = 'RSI Length - Default is usually 14, use 6 for volatile assets' //
) //
rsi_source = input( //
defval = close, //
title = 'RSI Source', //
tooltip = ' RSI Source - Default is Close' //
) //
Bullish_RSI = input.color( //
defval = #02ff02, //
title = 'Bullish RSI Color', //
tooltip = 'Color for Bullish RSI moves' //
) //
Bearish_RSI = input.color( //
defval = #ff0000, //
title = 'Bearish RSI Color', //
tooltip = 'Color for Bearish RSI moves' //
) //
rsi = ta.rsi(close, rsi_Length) //
rsi_bar_color = color.from_gradient(rsi, rsi_oversold_condition, rsi_overbought_condition, Bearish_RSI, Bullish_RSI) //
//BEGIN BAR COLOR SCRIPT========================================================================================================//
Color_The_Bars = rsi_bar_color //
barcolor(color_bars ? Color_The_Bars : na) //
//BEGINPRICELABELSCRIPT=========================================================================================================//
var label overbought_label1 = na //
var label oversold_label1 = na //
value_high = ta.rsi(close, rsi_Length) >= rsi_overbought_condition //
value_low = ta.rsi(close, rsi_Length) <= rsi_oversold_condition //
//BEGIN OVERBOUGHT AND OVERSOLD CONDITIONS======================================================================================//
//OVERBOUGHT //
midpoint_for_OB = (ta.highest(close, 30) + ta.lowest(close, 30)) / 2 //
if barstate.isrealtime and plot_obos_labels and value_high //
overbought_label1 := label.new(bar_index+10, midpoint_for_OB, //
text="Overbought: \n" + str.tostring(rsi), //
style=label.style_none, //
color=color.new(color.red, 0), //
textcolor=color.new(color.red, 0), //
xloc=xloc.bar_index, //
yloc=yloc.price, //
textalign=text.align_left) //
label.delete(overbought_label1[1]) //
//OVERSOLD //
midpoint_for_OS = (ta.highest(close, 30) + ta.lowest(close, 30)) / 2 //
if barstate.isrealtime and plot_obos_labels and value_low //
oversold_label1 := label.new(bar_index+10, midpoint_for_OS, //
text="Oversold: \n" + str.tostring(rsi), //
style=label.style_none, //
color=color.new(color.lime, 0), //
textcolor=color.new(color.lime, 0), //
xloc=xloc.bar_index, //
yloc=yloc.price, //
textalign=text.align_left) //
label.delete(oversold_label1[1]) //
//END CONDITION LABELS==========================================================================================================//
//ADD CURRENT PRICE LABEL //
//BEGIN PRICE LABEL script Code=================================================================================================//
var priceArray = array.new_float(0) //
array.push(priceArray, close) //
size = array.size(priceArray) //
price = array.get(priceArray, size -1) //
// //
//LABEL script for OPTIONAL PRICE LABEL=========================================================================================//
label pricelabel = na //
//label.new(x, y, text, xloc, yloc, color, style, textcolor, size, textalign, tooltip, text_font_family) //
if barstate.islast and show_current_price_label //
pricelabel := label.new(bar_index, //
y=0, //
yloc=yloc.abovebar, //
color = color.new(color.yellow, 0), //
style = label.style_none, //style_none, //
text="Current Price:\n" + str.tostring(array.get(priceArray, size -1)), //
textcolor = color.new(color.blue, 0)) //
label.delete(pricelabel[1]) //
//==============END SCRIPT======================================================================================================//
//BEGIN RSI Label script Code===================================================================================================//
var rsiArray = array.new_float(0) //
array.push(rsiArray, rsi) //
rsi_size = array.size(rsiArray) //
rsi_value = array.get(rsiArray, size -1) //
// //
//LABEL script for OPTIONAL PRICE LABEL=========================================================================================//
label rsilabel = na //
//label.new(x, y, text, xloc, yloc, color, style, textcolor, size, textalign, tooltip, text_font_family) //
if barstate.islast and plot_rsi_labels //
rsilabel := label.new(bar_index, //
y=0, //
yloc=yloc.belowbar, //
color = color.new(color.yellow, 0), //
style = label.style_none, //
text="\n\nCurrent \nRSI\nValue:\n" + str.tostring(array.get(rsiArray, size -1)), //
textcolor = color.new(color.blue, 0)) //
label.delete(rsilabel[1]) //
//==============END SCRIPT======================================================================================================// |
QQQ Fair Value Bands | https://www.tradingview.com/script/GQwWqXHC-QQQ-Fair-Value-Bands/ | dharmatech | https://www.tradingview.com/u/dharmatech/ | 92 | 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/
// © dharmatech
//@version=5
indicator("QQQ Fair Value Bands", overlay = true)
// fv = request.security("(WALCL - WTREGEN - RRPONTSYD)/1000/1000/1000*0.1 - 300", "D", close)
upper = request.security("(WALCL - WTREGEN - RRPONTSYD)/1000/1000/1000*0.1 - 310 + 30", "D", close)
fv = request.security("(WALCL - WTREGEN - RRPONTSYD)/1000/1000/1000*0.1 - 310", "D", close)
lower = request.security("(WALCL - WTREGEN - RRPONTSYD)/1000/1000/1000*0.1 - 310 - 20", "D", close)
plot(series=upper, title = 'Upper Band', color = color.red)
plot(series=fv, title = 'Fair Value', color=color.orange)
plot(series=lower, title = 'Lower Band', color=color.green)
|
Financial Data 8 Years | https://www.tradingview.com/script/IBUvevrN-Financial-Data-8-Years/ | morzor61 | https://www.tradingview.com/u/morzor61/ | 27 | 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
// Reference Works
// https://www.tradingview.com/script/Lbxl9OqZ-Financials-on-Chart/
// https://www.tradingview.com/script/yRFF3z4J-Financials-Comparing-Companies/
//@version=5
indicator("Financial Data 8 Years", shorttitle = 'FD8Y', format = format.volume)
//【 ◉ Constants 】――――――――――――――――――――――――――――――――――――――――――――――――――――――{
// Financial Periods.
string FQ = 'FQ'
string FY = 'FY'
string TTM = 'TTM'
// Financial Legends.
string F_NA = "⸺"
string F000 = "█ INCOME STATEMENTS █"
string F037 = " Total revenue"
string F004 = " Cost of goods"
string F015 = " Gross profit"
string F005 = " Deprecation and amortization"
string F018 = " Interest expense on debt"
string F034 = " Selling/general/admin expenses, total"
string F025 = " Operating income"
string F026 = " Operating expenses (excl. COGS)"
string F036 = " Total operating expenses"
string F013 = " EBITDA"
string F021 = " Net income"
string F010 = " Basic EPS"
string F100 = "█ BALANCE SHEET █"
string F155 = " Total assets"
string F156 = " Total current assets"
string F163 = " Total non-current assets"
string F161 = " Total liabilities"
string F157 = " Total current liabilities"
string F164 = " Total non-current liabilities"
string F159 = " Total equity"
string F162 = " Total liabilities & shareholders' equities"
string F158 = " Total debt"
string F152 = " Short term debt"
string F129 = " Long term debt"
string F101 = " Accounts payable"
string F102 = " Accounts receivable - trade, net"
string F160 = " Total inventory"
string F200 = "█ CASHFLOW █"
string F205 = " Cash from financing activities"
string F206 = " Cash from investing activities"
string F207 = " Cash from operating activities"
string F203 = " Capital expenditures"
string F219 = " Free cash flow"
string F300 = "█ STATISTICS █"
string F314 = " Debt to EBITDA ratio"
string F315 = " Debt to equity ratio"
string F319 = " Dividends per share - common stock primary issue"
string F323 = " EBITDA margin %"
string F335 = " Gross margin %"
string F347 = " Operating margin %"
string F344 = " Net margin %"
string F359 = " Return on equity %"
string F357 = " Return on assets %"
string F337 = " Interest coverage"
string F339 = " Inventory turnover"
string F400 = "█ CALCULATED █"
string F401 = " Market Capitalization"
string F402 = " Earnings Yield"
string F403 = " Price Book Ratio"
string F404 = " Price Earnings Ratio"
string F405 = " Price-To-Sales Ratio"
// --------------------------------------
var fqTimestamp = array.new_int()
var fyTimestamp = array.new_int()
var fqData1 = array.new_float()
var fyData1 = array.new_float()
var fyData2 = array.new_float()
var fyData3 = array.new_float()
var fyData4 = array.new_float()
// Create Year List
yearList = array.new_string()
// }
if timeframe.in_seconds(timeframe.period) < 86400
runtime.error("Please set the time frame 1Day or higher")
//【 ◉ Inputs 】――――――――――――――――――――――――――――――――――――――――――――――――――――――{
//
numOfYear = input.int(defval = 5, title = 'Number of Year', minval = 1, maxval = 9)
AnnualGroup = "Annual Data"
QuarterlyGroup = "Quarterly Data"
inputFyPeriod = input.string(FY, title = 'Period', options = [FY, FQ, TTM], group = AnnualGroup)
inputFqPeriod = input.string(FQ, title = 'Period', options = [FY, FQ, TTM], group = QuarterlyGroup)
fyItem1 = input.string(F037, title = 'Annual Data 1', options =[
F_NA, F000, F037, F004, F015, F005, F018, F034, F025, F026, F036,
F162, F158, F152, F129, F101, F160, F200, F205, F206, F207, F203, F219, F300,
F314, F315, F319, F323, F335, F347, F344, F359, F357, F337, F339,
F400, F401, F402, F403, F404, F405] , group = AnnualGroup)
fyItem2 = input.string(F021, title = 'Annual Data 2', options =[
F_NA, F000, F037, F004, F015, F005, F018, F034, F025, F026, F036,
F013, F021, F010, F100, F155, F156, F163, F161, F157, F164, F159,
F162, F158, F152, F129, F101, F160, F200, F205, F206, F207, F203, F219, F300,
F314, F315, F319, F323, F335, F347, F344, F359, F357, F337, F339,
F400, F401, F402, F403, F404, F405], group = AnnualGroup)
fyItem3 = input.string(F013, title = 'Annual Data 3', options =[
F_NA, F000, F037, F004, F015, F005, F018, F034, F025, F026, F036,
F013, F021, F010, F100, F155, F156, F163, F161, F157, F164, F159,
F162, F158, F152, F129, F101, F160, F200, F205, F206, F207, F203, F219, F300,
F314, F315, F319, F323, F335, F347, F344, F359, F357, F337, F339,
F400, F401, F402, F403, F404, F405], group = AnnualGroup)
fyItem4 = input.string(F010, title = 'Annual Data 4', options =[
F_NA, F000, F037, F004, F015, F005, F018, F034, F025, F026, F036,
F013, F021, F010, F100, F155, F156, F163, F161, F157, F164, F159,
F162, F158, F152, F129, F101, F160, F200, F205, F206, F207, F203, F219, F300,
F314, F315, F319, F323, F335, F347, F344, F359, F357, F337, F339,
F400, F401, F402, F403, F404, F405], group = AnnualGroup)
//
refFq = request.financial(syminfo.tickerid,"total_revenue", FQ, barmerge.gaps_on, ignore_invalid_symbol = true)
refFy = request.financial(syminfo.tickerid,"total_revenue", FY, barmerge.gaps_on, ignore_invalid_symbol = true)
tablePosY = input.string(defval = 'middle', title = 'Table Position', options = ['bottom', 'middle', 'top'], inline = 'table position' )
tablePosX = input.string(defval = 'left', title = '', options = ['left', 'center', 'right'], inline = 'table position' )
txtSize = input.string(defval = size.small, title = "Text Size", options = [size.tiny, size.small, size.normal, size.large])
dataDivider = input.float(defval = 1000000, title = "Million Divider")
// }
//
//【 ◉ Funtions 】――――――――――――――――――――――――――――――――――――――――――――――――――――――{
getId(simple string financialItem) =>
string result = switch financialItem
F004 => "COST_OF_GOODS"
F005 => "DEP_AMORT_EXP_INCOME_S"
F010 => "EARNINGS_PER_SHARE_BASIC"
F013 => "EBITDA"
F015 => "GROSS_PROFIT"
F018 => "INTEREST_EXPENSE_ON_DEBT"
F021 => "NET_INCOME"
F025 => "OPER_INCOME"
F026 => "OPERATING_EXPENSES"
F034 => "SELL_GEN_ADMIN_EXP_TOTAL"
F036 => "TOTAL_OPER_EXPENSE"
F037 => "TOTAL_REVENUE"
F101 => "ACCOUNTS_PAYABLE"
F102 => "ACCOUNTS_RECEIVABLES_NET"
F129 => "LONG_TERM_DEBT"
F152 => "SHORT_TERM_DEBT"
F155 => "TOTAL_ASSETS"
F156 => "TOTAL_CURRENT_ASSETS"
F157 => "TOTAL_CURRENT_LIABILITIES"
F158 => "TOTAL_DEBT"
F159 => "TOTAL_EQUITY"
F160 => "TOTAL_INVENTORY"
F161 => "TOTAL_LIABILITIES"
F162 => "TOTAL_LIABILITIES_SHRHLDRS_EQUITY"
F163 => "TOTAL_NON_CURRENT_ASSETS"
F164 => "TOTAL_NON_CURRENT_LIABILITIES"
F203 => "CAPITAL_EXPENDITURES"
F205 => "CASHffINANCING_ACTIVITIES"
F206 => "CASHf_INVESTING_ACTIVITIES"
F207 => "CASHf_OPERATING_ACTIVITIES"
F219 => "FREE_CASHfLOW"
F314 => "DEBT_TO_EBITDA"
F315 => "DEBT_TO_EQUITY"
F319 => "DPS_COMMON_STOCK_PRIM_ISSUE"
F323 => "EBITDA_MARGIN"
F335 => "GROSS_MARGIN"
F337 => "INTERST_COVER"
F339 => "INVENT_TURNOVER"
F344 => "NET_MARGIN"
F347 => "OPERATING_MARGIN"
F357 => "RETURN_ON_ASSETS"
F359 => "RETURN_ON_EQUITY"
=> ""
//
getFinancialData(item, period)=>
data = request.financial(syminfo.tickerid,getId(item), period,barmerge.gaps_off, ignore_invalid_symbol = true)
//
getDivider(item)=>
bool singleDigit = (
item == F010 or item == F314 or item == F315 or item == F319 or item == F323 or item == F335 or item == F347 or item == F344 or item == F359 or item == F357 or item == F337 or item == F339 or item == F400 or item == F401 or item == F402 or item == F403 or item == F404 or item == F405)
divider = singleDigit ? 1 : dataDivider
getSuffix(item)=>
div = getDivider(item)
len = str.tostring(div)
numberOfZero = str.length(len)-1
string suffix = na
if numberOfZero == 6
suffix := ",M"
else if numberOfZero == 9
suffix := ",B"
else if numberOfZero == 12
suffix := ",T"
else if numberOfZero == 3
suffix := ",K"
else
suffix := ""
//}
//
//【 ◉ Calculation 】――――――――――――――――――――――――――――――――――――――――――――――――――――――{
if refFq
array.unshift(fqTimestamp, time)
array.unshift(fqData1, getFinancialData(fyItem4, inputFqPeriod )/getDivider(fyItem4))
if refFy
array.unshift(fyTimestamp, time)
array.unshift(fyData1, getFinancialData(fyItem1, inputFyPeriod )/getDivider(fyItem1))
array.unshift(fyData2, getFinancialData(fyItem2, inputFyPeriod )/getDivider(fyItem2))
array.unshift(fyData3, getFinancialData(fyItem3, inputFyPeriod )/getDivider(fyItem3))
array.unshift(fyData4, getFinancialData(fyItem4, inputFyPeriod )/getDivider(fyItem4))
if barstate.islast
len = array.size(fqTimestamp)
string newYear = na
for i = 0 to len-1
yearText = str.format_time(array.get(fqTimestamp, i), 'yyyy')
if yearText != newYear
array.unshift(yearList, yearText)
newYear := yearText
int fqArraySize = na
int fyArraySize = na
int yearArraySize = na
if barstate.islast
fqArraySize := array.size(fqTimestamp)
fyArraySize := array.size(fyTimestamp)
yearArraySize := array.size(yearList)
//}
//
//【 ◉ Dispaly 】――――――――――――――――――――――――――――――――――――――――――――――――――――――{
var table result = na
if barstate.islast
// Annual Data
fyDataSize = array.size(fyTimestamp)
if numOfYear-1 >= yearArraySize
runtime.error("ERROR-01-FY : Pls set numOfYear to "+ str.tostring(yearArraySize))
if fyArraySize == 0
runtime.error('ERROR-02-FY : No data')
if fqArraySize == 0
runtime.error('ERROR-03-FQ : No data')
if yearArraySize == 0
runtime.error('ERROR-04-Year List : No data')
result := table.new(position = tablePosY+'_'+ tablePosX, columns =numOfYear+1, rows = 15, bgcolor = color.white, border_color = color.rgb(147, 149, 153), frame_color = color.rgb(179, 173, 173), border_width = 1 ,frame_width = 2)
table.cell(result,0, 0, 'Period', text_size = txtSize, text_color = color.rgb(10, 250, 18), bgcolor = color.rgb(55, 55, 58))
table.cell(result,0, 2, fyItem1+getSuffix(fyItem1), text_size = txtSize)
table.cell(result,0, 3, fyItem2+getSuffix(fyItem2), text_size = txtSize)
table.cell(result,0, 4, fyItem3+getSuffix(fyItem3), text_size = txtSize)
table.cell(result,0, 5, fyItem4+getSuffix(fyItem4), text_size = txtSize)
dataSize = array.size(yearList)
for i = 0 to numOfYear-1
// For loop for to create column header
// from left to right
table.cell(result, i+1, 0, array.get(yearList, dataSize-i-1), text_size = txtSize, text_color = color.rgb(10, 250, 18), bgcolor = color.rgb(55, 55, 58))
xYear = array.get(yearList, dataSize-i-1)
for y=0 to array.size(fyData1)-1
if str.format_time(array.get(fyTimestamp, y), format = 'yyyy') == xYear
table.cell(result,i+1, 2, str.tostring(array.get(fyData1, y),'#,##0.00'), text_size = txtSize, bgcolor = array.get(fyData1, y) < 0 ? color.rgb(255, 82, 82, 50) : na ,text_halign = text.align_right)
table.cell(result,i+1, 3, str.tostring(array.get(fyData2, y),'#,##0.00'), text_size = txtSize, bgcolor = array.get(fyData2, y) < 0 ? color.rgb(255, 82, 82, 50) : na ,text_halign = text.align_right)
table.cell(result,i+1, 4, str.tostring(array.get(fyData3, y),'#,##0.00'), text_size = txtSize, bgcolor = array.get(fyData3, y) < 0 ? color.rgb(255, 82, 82, 50) : na ,text_halign = text.align_right)
table.cell(result,i+1, 5, str.tostring(array.get(fyData4, y),'#,##0.00'), text_size = txtSize, bgcolor = array.get(fyData4, y) < 0 ? color.rgb(255, 82, 82, 50) : na ,text_halign = text.align_right)
// // Quarter Data
for i = 0 to numOfYear
// Create blank row.
table.cell(result, i, 1, '', height = 0.1, text_size = txtSize, bgcolor = color.rgb(2, 2, 2)) // create blank row.
table.cell(result,i, 6, '', height = 0.1, text_size = txtSize, bgcolor = color.rgb(2, 2, 2))
table.cell(result,i, 11, '', height = 0.1, text_size = txtSize, bgcolor = color.rgb(0, 0, 0))
for i = 1 to 4
// Create Quarter Label
// Top to bottom
table.cell(result,0, 6+i, 'Q'+str.tostring(5-i), text_size = txtSize)
string yearInFq = na
string monthInFq = na
for z = 0 to numOfYear-1
refYear = array.get(yearList, dataSize-z-1)
for i = 0 to array.size(fqTimestamp)-1
yearInFq := str.format_time(array.get(fqTimestamp, i), 'yyyy')
monthInFq := str.format_time(array.get(fqTimestamp, i), 'MMM')
if yearInFq == refYear
if monthInFq == 'Dec'
table.cell(result, z+1, 7, str.tostring(array.get(fqData1, i), '#,##0.00'), bgcolor = array.get(fqData1, i) < 0 ? color.rgb(255, 82, 82, 50) : na, text_size = txtSize)
if monthInFq == 'Sep'
table.cell(result, z+1, 8, str.tostring(array.get(fqData1, i), '#,##0.00'), bgcolor = array.get(fqData1, i) < 0 ? color.rgb(255, 82, 82, 50) : na,text_size = txtSize)
if monthInFq == 'Jun'
table.cell(result, z+1, 9, str.tostring(array.get(fqData1, i), '#,##0.00'), bgcolor = array.get(fqData1, i) < 0 ? color.rgb(255, 82, 82, 50) : na,text_size = txtSize)
if monthInFq == 'Mar'
table.cell(result, z+1, 10, str.tostring(array.get(fqData1, i), '#,##0.00'), bgcolor = array.get(fqData1, i) < 0 ? color.rgb(255, 82, 82, 50) : na,text_size = txtSize)
//}
|
Centred Moving Average | https://www.tradingview.com/script/q4aZWEbZ-Centred-Moving-Average/ | m_b_round | https://www.tradingview.com/u/m_b_round/ | 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/
// Edited by m_b_round
// With thanks to ValiantHero for the original idea, and also the explanation that appears below
// which is much better than I could have managed!
//
// ██╗░░░██╗░█████╗░██╗░░░░░██╗░█████╗░███╗░░██╗████████╗ ██╗░░██╗███████╗██████╗░░█████╗░
// ██║░░░██║██╔══██╗██║░░░░░██║██╔══██╗████╗░██║╚══██╔══╝ ██║░░██║██╔════╝██╔══██╗██╔══██╗
// ╚██╗░██╔╝███████║██║░░░░░██║███████║██╔██╗██║░░░██║░░░░███████║█████╗░░██████╔╝██║░░██║
// ░╚████╔╝░██╔══██║██║░░░░░██║██╔══██║██║╚████║░░░██║░░░░██╔══██║██╔══╝░░██╔══██╗██║░░██║
// ░░╚██╔╝░░██║░░██║███████╗██║██║░░██║██║░╚███║░░░██║░░░░██║░░██║███████╗██║░░██║╚█████╔╝
// ░░░╚═╝░░░╚═╝░░╚═╝╚══════╝╚═╝╚═╝░░╚═╝╚═╝░░╚══╝░░░╚═╝░░░░╚═╝░░╚═╝╚══════╝╚═╝░░╚═╝░╚════╝░
// QUICK REFERENCE
// Centered moving averages tries to resolve the problem that simple moving average are still not able to handle significant trends when forecasting
// When computing a running moving average in a centered way, placing the average in the middle time period makes sense
// If we average an even number of terms, we need to smooth the smoothed values
// Try to describe it with an example:
// The following table shows the results using a centered moving average of 4.
//
// nterim Steps
// Period Value SMA Centered
// 1 9
// 1.5
// 2 8
// 2.5 9.5
// 3 9 9.5
// 3.5 9.5
// 4 12 10.0
// 4.5 10.5
// 5 9 10.750
// 5.5 11.0
// 6 12
// 6.5
// 7 11
//
// This is the final table:
// Period Value Centered MA
// 1 9
// 2 8
// 3 9 9.5
// 4 12 10.0
// 5 9 10.75
// 6 12
// 7 11
//
// With this script we are able to process and display the centered moving average as described above.
// In addition to this, however, the script is also able to estimate the potential projection of future data based on the available data
// by replicating where necessary the data of the last bar until the number of data necessary for the calculation of the required centered moving average is reached.
//
// If for example I have 20 daily closings and I look for the moving average centered at 10, I receive the first data on the fifth day
// and the last data on the fourteenth day, so I have 5 days left uncovered, to remedy this I have to give the last value to the uncovered data
// the closing price of the last day.
// The deviations work like the bollinger bands but must refer to the centered moving average.
//@version=5
// @description This indicator is a centered moving average!
indicator("Centred Moving Average",max_lines_count = 500, overlay=true)
source = input.source(defval = high,title = 'source', group="Moving Average")
length = input.int(defval = 10,title = 'length', group="Moving Average")
lineSections = input.int(defval=50, title="Line sections", minval=1, maxval=150, tooltip="Steps to split the predicted line into - less steps = faster execution but more jagged line.", group="Moving Average")
dashLine = input.bool(false, "Dashed Line", tooltip="A dashed line will only draw every other section on the chart - again speed / processing savings over and above the white / red combo.", group="Moving Average")
future=input.bool(defval = true,title = 'show future', group="Moving Average")
double=input.bool(defval = false,title = 'use double moving average', group="Moving Average")
maColour = input.color(color.lime, "Line Colour", group="Moving Average")
plotStdDev = input.bool(true, "Plot Standard Deviation Bands", group="Standard Deviation")
stdDev = input.float(2.0, minval=0.001, maxval=50, title="Band multiplier", group="Standard Deviation")
stdDevColour = input.color(color.orange, "Band Colour", group="Standard Deviation")
offset = math.ceil(length/2)
average = ta.sma(source,length)
doubleAverage = ta.sma(ta.sma(source,length), length)
predictedValues = array.new_float()
predictedDSMAValues = array.new_float()
lastVal = source[0]
total = math.sum(source, length)
dsmaTotal = math.sum(average, length)
totalOffset = future ? offset * 2 : offset
if barstate.islast
for i = 1 to totalOffset
total := total - source[math.max(length - i, 0)] + lastVal
avg = total / length
array.push(predictedValues, avg)
if double
dsmaTotal := dsmaTotal - average[math.max(length - i, 0)] + avg
dsmaAvg = dsmaTotal / length
array.push(predictedDSMAValues, dsmaAvg)
plotall(data,dataGui,int xstart,float average,float dev)=>
ly=average+dev
step = 1
if array.size(data) > lineSections
step := math.ceil(array.size(data) / lineSections)
colorBool = true
lineColour = dev == 0 ? maColour : stdDevColour
for i=0 to array.size(data)-1 by step
y=array.get(data,i)+dev
if xstart + i + step < bar_index + 500
if (dashLine and not colorBool) or not dashLine
array.push(dataGui,line.new(xstart+i,ly,xstart+i+step,y,width = 1,color=colorBool ? color.white : lineColour))
ly:=y
colorBool := not colorBool
redesign(data,dataGui,int xstart,int offset,float average,float dev=0)=>
for g in dataGui
line.delete(g)
plotall(data,dataGui,xstart,average,0)
if (dev>0) and plotStdDev
plotall(data,dataGui,xstart,average,dev)
plotall(data,dataGui,xstart,average,-1*dev)
var data=array.new_float(0)
var dataGui=array.new_line(0)
length_BC_Tminus1_MAX = length
src_BC_Tminus1_MAX = double ? average : source
devMax = stdDev * ta.stdev(src_BC_Tminus1_MAX, length_BC_Tminus1_MAX)
upper = double ? doubleAverage + devMax : average + devMax
lower = double ? doubleAverage - devMax : average - devMax
plot(plotStdDev ? upper : na, "Upper", color=stdDevColour, offset = -offset)
plot(plotStdDev ? lower : na, "Lower", color=stdDevColour, offset = -offset)
// Plot SMA on the chart
plot(series=double ? doubleAverage : average ,offset = -offset, color=maColour, linewidth=2)
if barstate.islast
redesign(double ? predictedDSMAValues : predictedValues,dataGui,bar_index-offset,offset,double ? doubleAverage : average, devMax) |
TSG 5% Daily Calculator | https://www.tradingview.com/script/X8MnvRo1-TSG-5-Daily-Calculator/ | TheSecretsOfTrading | https://www.tradingview.com/u/TheSecretsOfTrading/ | 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/
// © TheSecretsOfTrading
//@version=5
indicator("TSG 5% Daily Calculator", overlay=true)
startBalance = input.float(50, "Initial Balance")
balance = input.float(0, "Current Balance")
dir = input.string("Long", "Trade Direction", options=["Long", "Short"])
lev = input.int(50, "Leverage")
risk = input.float(2.5, "Risk %")
goal = input.float(5, "Target %")
EntryPrice = input.float(0, "Entry Price")
EntryDate = input.time(timestamp("1 Feb 1989 12:00"), "Entry Date")
bool_table = input.bool(false, "Show Table")
table_size = input.string("Small", "Table Size", options =["Small","Normal"])
var bar_date = bar_index
if not EntryPrice
EntryPrice := close
if year(EntryDate) != 1989 and time == EntryDate
bar_date := bar_index
target_label_style = label.style_label_lower_left
loss_label_style = label.style_label_upper_left
//CALC
ROE = 100*(goal/risk)
TargetPrice = EntryPrice + (EntryPrice*ROE/100) / lev
StopLoss = EntryPrice - EntryPrice/lev
CurrentPercent = ( (close-EntryPrice) * goal ) / (TargetPrice-EntryPrice)
CurrentPrice = ( (close-EntryPrice) * (balance*goal/100) ) / (TargetPrice-EntryPrice)
CurrentPrice := CurrentPrice * -1
if dir == "Short"
TargetPrice := EntryPrice - (EntryPrice*ROE/100) / lev
StopLoss := EntryPrice + EntryPrice/lev
CurrentPercent := ( (EntryPrice-close) * goal ) / (EntryPrice-TargetPrice)
target_label_style := label.style_label_upper_left
loss_label_style := label.style_label_lower_left
targetColor = color.rgb(80, 217, 255)
stopLossColor = color.rgb(249, 78, 149)
boxColor = color.rgb(130, 199, 255)
entryColor = boxColor
colorbg = color.new(color.black, 75)
colorTransparent = color.new(color.rgb(0,0,0), 99)
s = size.normal
slarge = size.large
t = 80
entry_text = "$ " + str.tostring(EntryPrice)+" - "+dir+" " + str.tostring(lev) +"x"
target_text = str.tostring(goal)+"% Target "
loss_text = str.tostring(risk)+"% Stop Loss "
if balance > 0
entry_text += "\nCurrent Balance: $ " + str.tostring(balance) + "\nNext "+str.tostring(goal)+"% Profit: +" + str.tostring(math.round(balance*goal/100, 2)) + " $"
money_tp = balance*goal/100
money_sl = balance*risk/100
target_text += "( +"+str.tostring(money_tp)+" $ / Total: $ " + str.tostring(balance + money_tp)+" )"
loss_text += "( -"+str.tostring(money_sl)+" $ / Total: $ " + str.tostring(balance - money_sl)+" )"
else
entry_text += " )"
var entrypriceline = line.new(na,na,na,na, color=entryColor)
var boxTarget = box.new(na,na,na,na, bgcolor=color.new(targetColor, t), border_color=color.new(targetColor, t-7))
var boxStopLoss = box.new(na,na,na,na, bgcolor=color.new(stopLossColor, t), border_color=color.new(stopLossColor, t-7))
var _box = box.new(na,na,na,na, bgcolor = color.new(boxColor, t), border_color = color.new(boxColor, t-7) )
var _box_until_1M = box.new(na,na,na,na, bgcolor = color.new(boxColor, t), border_color = color.new(boxColor, t-40), xloc = xloc.bar_time)
var lab_target = label.new(na,na,target_text, textcolor=targetColor, color = colorbg, style=label.style_label_left, size = s)
var lab_stopLoss = label.new(na,na,loss_text, textcolor=stopLossColor, color = colorbg, style=label.style_label_left, size = s)
var lab_tpPrice = label.new(na,TargetPrice,str.tostring(TargetPrice), textcolor=targetColor, color = colorTransparent, style=target_label_style, size = slarge)
var lab_slPrice = label.new(na,StopLoss,str.tostring(StopLoss), textcolor=stopLossColor, color = colorTransparent, style=loss_label_style, size = slarge)
var lab_entry = label.new(na,na, entry_text, textcolor=entryColor, color = colorbg, style=label.style_label_left, size = s, textalign = text.align_left)
var lab_box = label.new(na,na,"", textcolor=boxColor, color = color.new(color.rgb(0,0,0), 99), style=label.style_label_left, size = slarge)
var lab_until_1M = label.new(na,na,"", textcolor=boxColor, color = color.new(color.rgb(0,0,0), 99), style=label.style_label_left, size = slarge, xloc = xloc.bar_time)
// TABLE
cells = 100
step = goal
start_table = startBalance
tcolor = color.white
t_size = table_size == "Small" ? size.small : size.normal
tablebgcolor = color.new(color.rgb(0,0,0), 5)
progressColor = color.new(color.green, 25)
columns = 5
var table _table = table.new(position.top_right, columns*2, cells+2, bgcolor = tablebgcolor, frame_color = color.gray)
if barstate.islast
//TABLES
d_1M = 0
d_done = 0
if bool_table
days = 0
col = 0
for i=0 to (cells / columns*2 )
col := 0
for a = i to i + columns - 1
value = math.round(start_table + (start_table*goal/100))
if value > 1000000 and d_1M == 0
d_1M := days - d_done
cellColor = tablebgcolor
if start_table < balance
cellColor := progressColor
if cellColor == tablebgcolor and d_done == 0
d_done := days
table.cell(_table, col, i, "Day " + str.tostring(days), text_color = tcolor, bgcolor = cellColor, text_size = t_size)
table.cell(_table, col+1, i, "$ " + str.tostring(start_table), text_color = tcolor, bgcolor = cellColor, text_size = t_size)
start_table := value
col += 2
days+=1
//Box Until 1 M
days_to_add = d_1M * 86400000 //Miliseconds
date = time + days_to_add
box.set_left(_box_until_1M, time)
box.set_right(_box_until_1M, date)
box.set_bottom(_box_until_1M, close - close/2)
box.set_top(_box_until_1M, close + close/2)
label.set_x(lab_until_1M, date)
label.set_y(lab_until_1M, close-close/2)
label.set_text(lab_until_1M, str.tostring(d_1M) + " days to become a Millionaire! ")
//LABELS
bar_shift = 5
bar_start = bar_index[bar_shift]
if year(EntryDate) != 1989
bar_start := bar_date
bar_end = bar_index + bar_shift
next_target = ""
label.set_x(lab_tpPrice, bar_end)
label.set_x(lab_slPrice, bar_end)
label.set_y(lab_tpPrice, TargetPrice)
label.set_y(lab_slPrice, StopLoss)
box.set_left(boxTarget, bar_start)
box.set_right(boxTarget, bar_end)
box.set_bottom(boxTarget, TargetPrice)
box.set_top(boxTarget, EntryPrice)
label.set_x(lab_target, bar_end)
label.set_y(lab_target, TargetPrice)
box.set_left(boxStopLoss, bar_start)
box.set_right(boxStopLoss, bar_end)
box.set_bottom(boxStopLoss, StopLoss)
box.set_top(boxStopLoss, EntryPrice)
label.set_x(lab_stopLoss, bar_end)
label.set_y(lab_stopLoss, StopLoss)
if EntryPrice
line.set_x1(entrypriceline, bar_start)
line.set_x2(entrypriceline, bar_end)
line.set_y1(entrypriceline, EntryPrice)
line.set_y2(entrypriceline, EntryPrice)
label.set_x(lab_entry, bar_end)
label.set_y(lab_entry, EntryPrice)
box.set_left(_box, bar_start)
box.set_right(_box, bar_index)
box.set_bottom(_box, EntryPrice)
box.set_top(_box, close)
box.set_bgcolor(_box, color.new(targetColor, t))
box.set_border_color(_box, color.new(targetColor, t-7))
label.set_x(lab_box, bar_end)
label.set_y(lab_box, close)
label.set_textcolor(lab_box, targetColor)
add = "+"
if CurrentPercent < 0
add:= ""
label.set_textcolor(lab_box, stopLossColor)
box.set_bgcolor(_box, color.new(stopLossColor, t))
box.set_border_color(_box, color.new(stopLossColor, t-7))
label.set_text(lab_box, add+str.tostring(math.round(CurrentPercent, 2)) + "% / " + add+str.tostring(math.round(CurrentPrice, 2)) + " $")
lab_dir = close >= EntryPrice ? label.style_label_upper_left : label.style_label_lower_left
label.set_style(lab_box, lab_dir)
|
Exhaustion Table [SpiritualHealer117] | https://www.tradingview.com/script/Jf3zLC8Q-Exhaustion-Table-SpiritualHealer117/ | spiritualhealer117 | https://www.tradingview.com/u/spiritualhealer117/ | 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/
// © spiritualhealer117
//@version=5
indicator("Exhaustion Table",overlay=true)
src = input.source(close, "Source")
c1 = input.color(color.red, "Color 1")
c2 = input.color(color.white,"Color 2")
stdev_len = input.int(300,"Standard Deviation Calculation Length")
calc_ppo(len) =>
(src-ta.ema(src,len))/ta.ema(src,len)
ppo15 = calc_ppo(15)
ppo30 = calc_ppo(30)
ppo50 = calc_ppo(50)
ppo100 = calc_ppo(100)
ppo300 = calc_ppo(300)
s1 = ta.stdev(ppo15,stdev_len)<ppo15?"↓":-ta.stdev(ppo15,stdev_len)>ppo15?"↑":"="
s2 = ta.stdev(ppo30,stdev_len)<ppo30?"↓":-ta.stdev(ppo30,stdev_len)>ppo30?"↑":"="
s3 = ta.stdev(ppo50,stdev_len)<ppo50?"↓":-ta.stdev(ppo50,stdev_len)>ppo50?"↑":"="
s4 = ta.stdev(ppo100,stdev_len)<ppo100?"↓":-ta.stdev(ppo100,stdev_len)>ppo100?"↑":"="
s5 = ta.stdev(ppo300,stdev_len)<ppo300?"↓":-ta.stdev(ppo300,stdev_len)>ppo300?"↑":"="
s21 = 2*ta.stdev(ppo15,stdev_len)<ppo15?"↓":-2*ta.stdev(ppo15,stdev_len)>ppo15?"↑":"="
s22 = 2*ta.stdev(ppo30,stdev_len)<ppo30?"↓":-2*ta.stdev(ppo30,stdev_len)>ppo30?"↑":"="
s23 = 2*ta.stdev(ppo50,stdev_len)<ppo50?"↓":-2*ta.stdev(ppo50,stdev_len)>ppo50?"↑":"="
s24 = 2*ta.stdev(ppo100,stdev_len)<ppo100?"↓":-2*ta.stdev(ppo100,stdev_len)>ppo100?"↑":"="
s25 = 2*ta.stdev(ppo300,stdev_len)<ppo300?"↓":-2*ta.stdev(ppo300,stdev_len)>ppo300?"↑":"="
if barstate.islast
exhaustion_table = table.new(position.top_right,4,6,color.new(c1,20),c2,1,c2,1)
table.cell(exhaustion_table,0,0,"Length", text_color = c2)
table.cell(exhaustion_table,1,0,"Exhaustion", text_color = c2)
table.cell(exhaustion_table,2,0,"σ", text_color = c2)
table.cell(exhaustion_table,3,0,"2σ", text_color = c2)
table.cell(exhaustion_table,1,1,str.tostring(math.round(ppo15,3)), text_color = c2)
table.cell(exhaustion_table,1,2,str.tostring(math.round(ppo30,3)), text_color = c2)
table.cell(exhaustion_table,1,3,str.tostring(math.round(ppo50,3)), text_color = c2)
table.cell(exhaustion_table,1,4,str.tostring(math.round(ppo100,3)), text_color = c2)
table.cell(exhaustion_table,1,5,str.tostring(math.round(ppo300,3)), text_color = c2)
table.cell(exhaustion_table,2,1,s1, text_color = c2)
table.cell(exhaustion_table,2,2,s2, text_color = c2)
table.cell(exhaustion_table,2,3,s3, text_color = c2)
table.cell(exhaustion_table,2,4,s4, text_color = c2)
table.cell(exhaustion_table,2,5,s5, text_color = c2)
table.cell(exhaustion_table,3,1,s21, text_color = c2)
table.cell(exhaustion_table,3,2,s22, text_color = c2)
table.cell(exhaustion_table,3,3,s23, text_color = c2)
table.cell(exhaustion_table,3,4,s24, text_color = c2)
table.cell(exhaustion_table,3,5,s25, text_color = c2)
table.cell(exhaustion_table,0,1,"15", text_color = c2)
table.cell(exhaustion_table,0,2,"30", text_color = c2)
table.cell(exhaustion_table,0,3,"50", text_color = c2)
table.cell(exhaustion_table,0,4,"100", text_color = c2)
table.cell(exhaustion_table,0,5,"300", text_color = c2) |
VS Score [SpiritualHealer117] | https://www.tradingview.com/script/Qi3U7LxL-VS-Score-SpiritualHealer117/ | spiritualhealer117 | https://www.tradingview.com/u/spiritualhealer117/ | 65 | 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/
// © spiritualhealer117
// Disclaimer
// This indicator was created for informational purposes, and does not constitute my financial or investment advice
// Every model comes with limitations, and so results produced by this model should not be relied on excessively
//@version=5
indicator("VS Score [SpiritualHealer117]",max_lines_count = 2,overlay=true, max_boxes_count = 1)
//1 - Inputs {
//1.1 Inputs for Price Percentage Oscillator
ppo_len = input.int(50,"PPO Length")
ppo_sens = input.float(0.1,"PPO Extreme Threshold")
//1.2 Inputs for Volume Histogram
v_len = input.int(50, "Volume Histogram Length")
v_src = volume
//1.3 Inputs for Past State Calculation
rare_sens = input.float(2, "Abnormal Sensitivity")
normal_sens = input.float(0.5, "Normal Sensitivity")
//1.4 Inputs for Moving Average
ma_len = input.int(14, "Moving Average Length")
// 1.5 Length for data fitting
data_fit_len = input.int(1000, "Data fitting period")
//1.5 Other Options
src = input.source(hl2,"Source")
ma_type = input.string("SMA","MA Smoothing Option", ["SMA","WMA","EMA","RMA", "VWMA"])
//1.6 Inputs for Styling and Coloring
bclr = input.color(color.black,"Border Color")
bgclr = input.color(color.rgb(78, 218, 57),"Gain Color")
bgclr2 = input.color(color.rgb(230, 185, 185),"Loss Color")
bgclr3 = input.color(color.rgb(206, 206, 206),"Neutral Color")
//}
//2 - Indicator State Calculations {
//2.1 Calculation for Moving Average (0-1) and PPO (-1-1) {
calc_moving_average(ma_type,src,length)=>
if ma_type == "SMA"
ta.sma(src,length)
else if ma_type == "WMA"
ta.wma(src,length)
else if ma_type == "EMA"
ta.ema(src,length)
else if ma_type == "RMA"
ta.rma(src, length)
else
ta.vwma(src, length)
ma = calc_moving_average(ma_type,src,ma_len)
src2ma_diff = src-ma
ma_state = src2ma_diff > 0 ? 1:0
ppo_ma = calc_moving_average(ma_type,src,ppo_len)
ppo = (src-ppo_ma)/ppo_ma
ppo_state = ppo > ppo_sens?-1:(ppo < -ppo_sens?1:0)
//}
//2.2 Calculation of Past State (1-5) {
ret = (src-src[1])/src[1]
ret_dev = ta.stdev(ret,ma_len)
ret_ma = calc_moving_average(ma_type,ret,ma_len)
state = ret > rare_sens * ret_dev+ret_ma ? 5 : ret > normal_sens* ret_dev+ret_ma ? 4 : ret > -normal_sens* ret_dev+ret_ma ? 3 : ret > -rare_sens * ret_dev+ret_ma ? 2 : 1
past_state=state[1]
//}
//2.3 Calculation for Volume Histogram {
volume_histogram = array.new<float>(5,0)
array.set(volume_histogram,0,math.sum(state==1?v_src:0,v_len))
array.set(volume_histogram,1,math.sum(state==2?v_src:0,v_len))
array.set(volume_histogram,2,math.sum(state==3?v_src:0,v_len))
array.set(volume_histogram,3,math.sum(state==4?v_src:0,v_len))
array.set(volume_histogram,4,math.sum(state==5?v_src:0,v_len))
vh_state = array.indexof(volume_histogram,array.max(volume_histogram))
//}
//2.4 Other Important Calculations {
relevant_close = barstate.isconfirmed?close:close[1]
extreme_gain_price = (rare_sens * ret_dev+ 1)*relevant_close
gain_price = (normal_sens * ret_dev + 1)*relevant_close
flat_price = (1)*relevant_close
loss_price = (-normal_sens * ret_dev + 1)*relevant_close
extreme_loss_price = (-rare_sens * ret_dev+ 1)*relevant_close
//}
//}
//3 - Probability Vector Calculations {
//3.1 General Calculation Function {
create_probability_vector(indicator_state, state, data_len)=>
output_vector = array.new<float>(5,0)
for i = 0 to 4
sum = 0
for j = 0 to data_len
indic_condition = indicator_state[j] == indicator_state and state[j]==i+1 ? 1 : 0
sum := sum + indic_condition
array.set(output_vector,i,sum)
output_vector
//}
//3.2 Vector Transformation {
vt(vector)=>
transformed_vector = array.new<float>(5,0)
for i = 0 to 4
array.set(transformed_vector,i,array.get(vector,i)/array.sum(vector))
transformed_vector
//}
//3.3 Individual Calculations {
ppo_vector = vt(create_probability_vector(ppo_state, state, data_fit_len))
ma_vector = vt(create_probability_vector(ma_state, state, data_fit_len))
vh_vector = vt(create_probability_vector(vh_state,state,data_fit_len))
past_vector = vt(create_probability_vector(past_state,state,data_fit_len))
//}
//}
//4 - VS Score Calculation {
//4.1 Vector Combination {
vs_combined_vector = array.new<float>(5,0)
for i = 0 to 4
array.set(vs_combined_vector,i,array.get(ppo_vector,i)+array.get(ma_vector,i)+array.get(vh_vector,i)+array.get(past_vector,i))
vs_probability_vector = vt(vs_combined_vector)
//}
//}
//5 - Output {
//5.1 Tabular Output {
output_table = table.new(position = position.middle_right, columns = 2, rows = 6, bgcolor = bgclr, border_width = 1)
if barstate.islast
table.cell(table_id = output_table, column = 0, row = 0, text = "Move Type")
table.cell(table_id = output_table, column = 1, row = 0, text = "p")
table.cell(table_id = output_table, column = 0, row = 1, text = "Extreme Rise")
table.cell(table_id = output_table, column = 0, row = 2, text = "Rise")
table.cell(table_id = output_table, column = 0, row = 3, text = "Flat")
table.cell(table_id = output_table, column = 0, row = 4, text = "Fall")
table.cell(table_id = output_table, column = 0, row = 5, text = 'Extreme Fall')
for i = 0 to 4
table.cell(table_id = output_table, column = 1, row = i+1, text = str.tostring(math.round(array.get(vs_probability_vector,i),3)))
b = box.new(bar_index,gain_price,bar_index+5,loss_price,bclr,border_width = 1, xloc=xloc.bar_index, bgcolor = bgclr3, text=str.tostring(math.round(array.get(vs_probability_vector,2),2)),text_size=size.small)
b2 = box.new(bar_index,extreme_gain_price,bar_index+5,gain_price,bclr,border_width = 1, xloc=xloc.bar_index, bgcolor = bgclr, text=str.tostring(math.round(array.get(vs_probability_vector,1),2)),text_size=size.small)
b3=box.new(bar_index,extreme_loss_price,bar_index+5,loss_price,bclr,border_width = 1, xloc=xloc.bar_index, bgcolor = bgclr2, text=str.tostring(math.round(array.get(vs_probability_vector,3),2)),text_size=size.small)
//}
//} |
Strongest Supports And Resistances | https://www.tradingview.com/script/MuadnUsW-Strongest-Supports-And-Resistances/ | mccshuka | https://www.tradingview.com/u/mccshuka/ | 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/
// © mertcancucen
//@version=5
indicator("Strongest Supports And Resistances", "SSAR", true, max_bars_back = 480)
var GRP = "SR Parameters"
var GRP1 = "SR Power Factors"
var GRP2 = "SR Visualization"
closeness_ = input.float(0.005, "Closeness", tooltip = "Higer the value, far away the lines from candles", group = GRP, maxval = 0.5, minval = 0.00001, step = 0.001)
similarity_ = input.float(0.5, "Similarity", tooltip = "Line similarity threshold. Higher the value, more different the lines", group = GRP, maxval = 1, minval = 0.1, step = 0.05)
minHitCount = input.int(6, "Minimum Hit Count", tooltip = "Required amount of hits for an SR line to have a strength", group = GRP, maxval = 30, minval = 2, step = 1)
lookBack = input.int(40, "Look Back", tooltip = "How many bars from the last you want to count in", group = GRP, maxval = 100, minval = 10, step = 1)
maxBarBack_ = input.int(150, "Max Bar Back", tooltip = "How many bars back are counted for hits", group = GRP, maxval = 400, minval = 10, step = 1)
useLogarithmic = input(true, "Logarithmic", "If the graph is logarithmic, make it true", group = GRP)
dontCountAfter = input.time(0, "Hide bars after", "To test the algorithm, you can hide some latest bars", group = GRP)
UTC = input.float(3.0, title = "UTC Timezone offset", group = GRP)
countPower = input.float(1.0, "Hit Factor", tooltip = "Coefficient for line hits on candles", inline= "1", group = GRP1, maxval = 2, minval = 0.1, step = 0.1)
weightLatest = input(false, "Weight Latest Hit", "SR lines tend to have more close to latest candles", inline= "11", group = GRP1)
weightLatestPower = input.float(0.3, "Factor", inline= "11", group = GRP1, maxval = 0.75, minval = 0.1, step = 0.05)
weightDuration = input(false, "Weight Longer Hit", "If an SR line hits spread through chart, it gets more valueable", inline= "21", group = GRP1)
weightDurationPower = input.float(0.3, "Factor", inline= "21", group = GRP1, maxval = 0.75, minval = 0.1, step = 0.05)
weightVolume = input(true, "Weight Volume Hit", "If an SR line hits on more volume, it gets more valuable ", inline= "31", group = GRP1)
weightVolumePower = input.float(0.3, "Factor", inline= "31", group = GRP1, maxval = 0.75, minval = 0.1, step = 0.05)
weightStreak = input(true, "Weight Max Streak", "If an SR line doesn't get broken, it gets more valuable ", inline= "41", group = GRP1)
weightStreakPower = input.float(0.3, "Factor", inline= "41", group = GRP1, maxval = 0.75, minval = 0.1, step = 0.05)
totalLines = input.int(15, "Total Lines Shown", tooltip = "Count of strongest lines shown", group = GRP2, maxval = 40, minval = 5, step = 1)
showWickLines = input(true, "Show Through Wicks", "SR lines that are drawn through wicks", inline= "41", group = GRP2)
showBodyLines = input(true, "Show Through Open-Closes", "SR lines that are drawn through opens and closes", inline= "51", group = GRP2)
color wickColor = input(#ff00ffaf, "Wick Color", "SR lines that are drawn through wicks", inline= "41", group = GRP2)
color bodyColor = input(#ff7b00, "Body Color", "SR lines that are drawn through opens and closes", inline= "51", group = GRP2)
can_we_start(prd, UTC)=>
// get UTC time
int timenow_ = timenow + math.round(UTC * 3600000)
int time_ = time + math.round(UTC * 3600000)
// calculate D/H/M/S for the bar which we are on and time now
int daynow_ = math.floor((timenow_ + 86400000 * 3) / 86400000) % 7
int day_ = math.floor((time_ + 86400000 * 3) / 86400000) % 7
int hournow_ = math.floor(timenow_ / 3600000) % 24
int hour_ = math.floor(time_ / 3600000) % 24
int minutenow_ = math.floor(timenow_ / 60000) % 60
int minute_ = math.floor(time_ / 60000) % 60
int secondnow_ = math.floor(timenow_ / 60000) % 60
int second_ = math.floor(time_ / 60000) % 60
int hmstime_ = hour_ * 3600000 + minute_ * 60000 + second_ * 1000
int hmstimenow_ = hournow_ * 3600000 + minutenow_ * 60000 + secondnow_ * 1000
var int starttime = na
if bar_index > prd and (na(starttime) or time_ < nz(starttime))
if timeframe.isdaily
if day_ == daynow_ // session day
diff = time_ - time_[prd]
starttime := timenow_ - diff
if daynow_ > day_ and daynow_ > day_[1] and day_[1] > day_ // weekend
diff = time_[1] - time_[prd + 1] + (daynow_ - day_[1]) * 86400000
starttime := timenow_ - diff
if timeframe.isintraday
if day_ == daynow_ and day_[1] == daynow_ and hmstime_ > hmstimenow_ and hmstime_[1] <= hmstimenow_ // in session
diff = time_[1] - time_[prd + 1] + math.round(UTC * 3600000)
starttime := timenow_ - diff
if day_ != daynow_ and day_[1] == daynow_ and hmstime_ < hmstimenow_ and hmstime_[1] <= hmstimenow_ // in same day and after session
diff = time_[1] - time_[prd + 1] + (hmstimenow_ - hmstime_[1]) + math.round(UTC * 3600000)
starttime := timenow_ - diff
if day_ == daynow_ and day_[1] + 1 == daynow_ and hmstime_ > hmstimenow_ and hmstime_[1] >= hmstimenow_ // in week (not first day) and before session
diff = time_[1] - time_[prd + 1] + (24 * 3600000 - hmstime_[1]) + hmstimenow_ + math.round(UTC * 3600000)
starttime := timenow_ - diff
if day_ == daynow_ and day_[1] > daynow_ and hmstime_ > hmstimenow_ and hmstime_[1] >= hmstimenow_ // the day after weekend before session
diff = time_[1] - time_[prd + 1] + 2 * 86400000 + (24 * 3600000 - hmstime_[1]) + hmstimenow_ + math.round(UTC * 3600000)
starttime := timenow_ - diff
if daynow_ > day_ and daynow_ > day_[1] and day_[1] > day_ // weekend
diff = time_[1] - time_[prd + 1] + (daynow_ - day_[1] - 1) * 86400000 + (24 * 3600000 - hmstime_[1]) + hmstimenow_ + math.round(UTC * 3600000)
starttime := timenow_ - diff
if timeframe.isweekly
starttime := timenow_ - timeframe.multiplier * prd * 604800000 // 1 week = 604800000ms
if timeframe.ismonthly
starttime := timenow_ - timeframe.multiplier * prd * 2629743000 // 1 month = 2629743000ms
not na(starttime) and time >= starttime
var similarity = similarity_
var closeness = closeness_
var useBarIndexSet = false
var currentTimeStamp = timenow
var startBarIndex = -1
var startBarTime = -1
var weStarted = false
var maxBarBack = maxBarBack_
if(dontCountAfter <= currentTimeStamp)
line.new(dontCountAfter, 0, dontCountAfter, 1, xloc.bar_time, extend.both, color.blue, line.style_dashed, 1)
type Line
float slope
int x
float y
bool isLog
type RSLine
Line _line
int[] hitTimes
int[] crossTimes
float totalVolume
float totalCrossVolume
bool isShadows
float power
int barIndex
int lastCalculation
method checkArraySimilarity(int[] arr1, int[] arr2) =>
size1 = array.size(arr1)
size2 = array.size(arr2)
if(size1 > 0 and size2 > 0)
bigArr = size1 > size2 ? arr1 : arr2
smallArr = size1 > size2 ? arr2 : arr1
sameCount = 0
for i = 0 to (array.size(smallArr) - 1)
if(array.indexof(bigArr, array.get(smallArr, i)) > -1)
sameCount := sameCount + 1
if(array.size(bigArr) == 1)
sameCount == 1
else if(array.size(bigArr) == 2)
sameCount == 2
else if(sameCount > 0 and sameCount >= math.round(array.size(bigArr) * similarity))
true
else
false
else
array.size(arr1) == 0 and array.size(arr2) == 0
method checkIfSame(RSLine line1, RSLine line2) =>
checkArraySimilarity(line1.hitTimes, line2.hitTimes)
method calculateMaxStreakTime(int[] crossTimes) =>
int timeMax = dontCountAfter == 0 ? currentTimeStamp : dontCountAfter
int timeMin = startBarTime
int maxStreak = -1
if(array.size(crossTimes) == 0)
maxStreak := timeMax - timeMin
else
int[] sortedIndices = array.sort_indices(crossTimes)
for j = 0 to (array.size(crossTimes) - 1)
currentStreak = 0
if(j == 0)
currentStreak := array.get(crossTimes, array.get(sortedIndices, j)) - timeMin
else if(j == (array.size(crossTimes) - 1))
currentStreak := timeMax - array.get(crossTimes, array.get(sortedIndices, j))
else
currentStreak := array.get(crossTimes, array.get(sortedIndices, j)) - array.get(crossTimes, array.get(sortedIndices, j - 1))
if(currentStreak > maxStreak)
maxStreak := currentStreak
maxStreak
method calculatePower(RSLine line1) =>
power = 0.0
hitCount = array.size(line1.hitTimes) - array.size(line1.crossTimes)
if(hitCount >= minHitCount)
power := math.pow(hitCount, countPower)
if(weightDuration)
power := power * math.pow(array.max(line1.hitTimes) - array.min(line1.hitTimes), weightDurationPower)
if(weightLatest)
power := power * (1 / math.pow(currentTimeStamp - array.max(line1.hitTimes), weightLatestPower))
if(weightStreak)
power := power * math.pow(calculateMaxStreakTime(line1.crossTimes) , weightStreakPower)
if(weightVolume and line1.totalVolume - line1.totalCrossVolume > 0)
power := power * math.pow(line1.totalVolume - line1.totalCrossVolume, weightVolumePower)
power
method calculateValFor(Line line1, int x) =>
transition = line1.y - line1.x * line1.slope
x * line1.slope + transition
method tradingViewPlot(Line line1, float alpha, bool isWick) =>
x2 = line1.x + 30 * 24 * 60 * 60 * 1000
y1 = line1.y
y2 = calculateValFor(line1, x2)
if(useLogarithmic)
y1 := math.exp(y1)
y2 := math.exp(y2)
lineColor = color.new(isWick ? wickColor : bodyColor, alpha * 100)
line.new(line1.x, y1, x2, y2, xloc.bar_time, extend.both, color=lineColor, style=line.style_solid, width = isWick ? 1 : 2)
method setTimeForRsLine(RSLine rsLine, int datumTime, float volume, bool isCross) =>
if(isCross)
if(array.indexof(rsLine.crossTimes, datumTime) == -1)
array.push(rsLine.crossTimes, datumTime)
rsLine.totalCrossVolume := rsLine.totalCrossVolume + volume
else
if(array.indexof(rsLine.hitTimes, datumTime) == -1)
array.push(rsLine.hitTimes, datumTime)
rsLine.totalVolume := rsLine.totalVolume + volume
method sortRSLines(RSLine[] rsLines) =>
powers = array.new_float(0)
rsLinesWithPower = array.new<RSLine>(0)
for i = 0 to (array.size(rsLines) - 1)
rsLine = array.get(rsLines, i)
rsLine.power := calculatePower(rsLine)
if(rsLine.power > 0)
array.push(powers, rsLine.power)
array.push(rsLinesWithPower, rsLine)
sortedIndices = array.sort_indices(powers)
sortedArray = array.new<RSLine>(0)
if(array.size(rsLinesWithPower) > 0)
for i = 0 to (array.size(rsLinesWithPower) - 1)
array.push(sortedArray, array.get(rsLinesWithPower, array.get(sortedIndices, (array.size(rsLinesWithPower) - 1) - i)))
sortedArray
method removeCloseLines(RSLine[] lines_) =>
if(array.size(lines_) <= 1)
lines_
else
lines = sortRSLines(lines_)
if(array.size(lines) > 0)
rsLines = array.new<RSLine>(0)
for i = 0 to (array.size(lines) - 1)
found = false
index = array.size(lines) - i - 1
for j = 0 to (index - 1)
index2 = (index - 1) - j
if(index2 > 0)
if(checkIfSame(array.get(lines, index), array.get(lines, index2)))
found := true
break
if(not found)
array.push(rsLines, array.get(lines, index))
sortRSLines(rsLines)
else
lines
method calculateMissingRSLineData(RSLine rsLine, bool log) =>
if(bar_index - rsLine.barIndex < maxBarBack)
for i = rsLine.lastCalculation + 1 to bar_index
datumTime = time[bar_index - i]
lineYValue = calculateValFor(rsLine._line, datumTime)
datumOpen = open[bar_index - i]
datumClose = close[bar_index - i]
datumLow = low[bar_index - i]
datumHigh = high[bar_index - i]
if(log)
datumOpen := math.log(datumOpen)
datumClose := math.log(datumClose)
datumLow := math.log(datumLow)
datumHigh := math.log(datumHigh)
lowLevelLine = 0.0
highLevelLine = 0.0
if(lineYValue > 0)
lowLevelLine := lineYValue * (1 - closeness)
highLevelLine := lineYValue * (1 + closeness)
else
lowLevelLine := lineYValue * (1 + closeness)
highLevelLine := lineYValue * (1 - closeness)
if(rsLine.isShadows)
if((datumLow >= lowLevelLine and datumLow <= highLevelLine) or (datumHigh >= lowLevelLine and datumHigh <= highLevelLine))
setTimeForRsLine(rsLine, datumTime, na(volume[bar_index - i]) ? 0 : volume[bar_index - i], false)
else if((datumLow <= lowLevelLine and datumHigh >= highLevelLine))
setTimeForRsLine(rsLine, datumTime, na(volume[bar_index - i]) ? 0 : volume[bar_index - i], true)
else
if((datumOpen >= lowLevelLine and datumOpen <= highLevelLine) or (datumClose >= lowLevelLine and datumClose <= highLevelLine))
setTimeForRsLine(rsLine, datumTime, na(volume[bar_index - i]) ? 0 : volume[bar_index - i], false)
else if((datumClose > datumOpen and datumOpen <= lowLevelLine and datumClose >= highLevelLine) or (datumClose <= datumOpen and datumClose <= lowLevelLine and datumOpen >= highLevelLine))
setTimeForRsLine(rsLine, datumTime, na(volume[bar_index - i]) ? 0 : volume[bar_index - i], true)
rsLine.lastCalculation := bar_index
rsLine
method calculateRSLineData(Line line1, bool useShadows, bool log) =>
rsLine = RSLine.new(line1, array.new_int(0), array.new_int(0), 0, 0, useShadows, 0.0, bar_index, math.max(1, startBarIndex) - 1)
calculateMissingRSLineData(rsLine, log)
method findRSLines(bool log) =>
rsLines = array.new<RSLine>(0)
for i = math.max(0, bar_index - 1 - lookBack) to math.max(0, bar_index - 1)
barLow = low[0]
barHigh = high[0]
barOpen = open[0]
barClose = close[0]
datumLow = low[bar_index - i]
datumHigh = high[bar_index - i]
datumOpen = open[bar_index - i]
datumClose = close[bar_index - i]
datumOpenTime = time[bar_index - i]
barOpenTime = time[0]
if(log)
barLow := math.log(barLow)
barHigh := math.log(barHigh)
barOpen := math.log(barOpen)
barClose := math.log(barClose)
datumLow := math.log(datumLow)
datumHigh := math.log(datumHigh)
datumOpen := math.log(datumOpen)
datumClose := math.log(datumClose)
line1 = Line.new(((datumLow - barLow) / (datumOpenTime - barOpenTime)), barOpenTime, barLow, log)
line2 = Line.new(((datumHigh - barLow) / (datumOpenTime - barOpenTime)), barOpenTime, barLow, log)
line3 = Line.new(((datumOpen - barOpen) / (datumOpenTime - barOpenTime)), barOpenTime, barOpen, log)
line4 = Line.new(((datumClose - barOpen) / (datumOpenTime - barOpenTime)), barOpenTime, barOpen, log)
line5 = Line.new(((datumLow - barHigh) / (datumOpenTime - barOpenTime)), barOpenTime, barHigh, log)
line6 = Line.new(((datumHigh - barHigh) / (datumOpenTime - barOpenTime)), barOpenTime, barHigh, log)
line7 = Line.new(((datumOpen - barClose) / (datumOpenTime - barOpenTime)), barOpenTime, barClose, log)
line8 = Line.new(((datumClose - barClose) / (datumOpenTime - barOpenTime)), barOpenTime, barClose, log)
if(showWickLines)
rsLines.push(calculateRSLineData(line1, true, log))
rsLines.push(calculateRSLineData(line2, true, log))
rsLines.push(calculateRSLineData(line5, true, log))
rsLines.push(calculateRSLineData(line6, true, log))
if(showBodyLines)
rsLines.push(calculateRSLineData(line3, false, log))
rsLines.push(calculateRSLineData(line4, false, log))
rsLines.push(calculateRSLineData(line7, false, log))
rsLines.push(calculateRSLineData(line8, false, log))
removed = removeCloseLines(rsLines)
if(array.size(removed) > 0)
array.slice(removed, 0 , math.min(array.size(removed), math.max(totalLines, 30)))
else
removed
var rsLines = array.new<RSLine>(0)
if(not useBarIndexSet)
if(bar_index > 0)
openTime = time[bar_index - 1]
closeTime = time_close[bar_index - 1]
if(closeTime - openTime <= 60 * 60 * 1000)
similarity := similarity * 1.6
closeness := closeness / 4
else if(closeTime - openTime <= 4 * 60 * 60 * 1000)
similarity := similarity * 1.35
closeness := closeness / 3
else if(closeTime - openTime <= 24 * 60 * 60 * 1000)
similarity := similarity * 1.2
closeness := closeness / 2
else if(closeTime - openTime <= 3 * 24 * 60 * 60 * 1000)
similarity := similarity * 1.1
closeness := closeness / 1.5
useBarIndexSet := true
if(not weStarted)
weStarted := can_we_start(maxBarBack, UTC)
if(weStarted)
if(startBarIndex == -1)
startBarIndex := bar_index
startBarTime := time
if(array.size(rsLines) > 1 and (dontCountAfter >= time or dontCountAfter == 0))
for j = 0 to (array.size(rsLines) - 1)
rsLine = array.get(rsLines, j)
if(rsLine.barIndex > bar_index - maxBarBack)
calculateMissingRSLineData(rsLine, useLogarithmic)
if(not barstate.islast and (dontCountAfter >= time or dontCountAfter == 0))
linesForBar = findRSLines(useLogarithmic)
if(array.size(linesForBar) > 0)
for j = 0 to (array.size(linesForBar) - 1)
array.push(rsLines, array.get(linesForBar, j))
if(bar_index % 20 == 0 or (bar_index % 5 and array.size(rsLines) > 100))
rsLines := removeCloseLines(rsLines)
if(array.size(rsLines) > 0)
rsLines := array.slice(rsLines, 0 , math.min(array.size(rsLines), totalLines * 5))
if(barstate.islast)
removed = removeCloseLines(rsLines)
if(array.size(removed) > 0)
removed := array.slice(removed, 0 , math.min(array.size(removed), totalLines))
for i = 0 to (array.size(removed) - 1)
rsLine = array.get(removed, i)
tradingViewPlot(rsLine._line, i * 0.8 / array.size(removed), rsLine.isShadows)
else
label.new(bar_index, close, "Nothing found. Please adjust some parameters. ex. decrease max bar back parameter to available bar count at your current chart.")
else if(barstate.islast)
label.new(bar_index, close, "Please decrease max bar back parameter to available bar count at your current chart.")
|
Auto anchored VWAP Highest/Lowest Last 'n' bars | https://www.tradingview.com/script/5vTue3Gz-Auto-anchored-VWAP-Highest-Lowest-Last-n-bars/ | TJalam | https://www.tradingview.com/u/TJalam/ | 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/
// © Badshah.E.Alam
//@version=5
indicator("Auto anchored VWAP Highest/Lowest Last 'n' bars ", overlay=true,max_labels_count = 500,max_lines_count = 500, max_bars_back = 3000)
len = input.int(100,'bars to look for Highest/Lowest ',maxval = 3000)
src = input.source(hlc3,'source')
hiOffset = - ta.highestbars(src,len)
loOffset = - ta.lowestbars(src,len)
htf=''
//function to calculate and store the vwap values
f_avwap(src, date) =>
float[] array_sumSrc = array.new_float( date,na)
float[] array_sumVol = array.new_float( date,na)
float[] array_final = array.new_float( date,na)
int[] bar_finaltime = array.new_int( date,na)
if date>0 and array.size(array_sumSrc)>0
for i=date-1 to 0
sumSrc = src[i] * volume[i]
sumVol = volume[i]
array.set(array_sumSrc,i,sumSrc + sumSrc[1+i])
array.set(array_sumVol,i,sumVol + sumVol[1+i])
// sumSrc := sumSrc + sumSrc[1+i]
// sumVol := sumVol + sumVol[1+i]
finalVal=array.sum(array_sumSrc) / array.sum(array_sumVol)
array.set(array_final,i,finalVal)
array.set(bar_finaltime,i,time_close)
[array_final,bar_finaltime]
// get vwap from highest from last 'n' bars
ath_dt = bar_index-bar_index[hiOffset]
[final_val,barTime]=request.security(syminfo.tickerid,htf,f_avwap(src, ath_dt))
// get vwap from lowest from last 'n' bars
atl_dt = bar_index-bar_index[loOffset]
[final_vallo,barTimelo]=request.security(syminfo.tickerid,htf,f_avwap(src, atl_dt))
alertML=input.string('touch Low Auto VWAP',title ='Auto VWAP lowest touch Alert message',group = 'Alert Message')
alertMH=input.string('touch High Auto VWAP',title ='Auto VWAP highest touch Alert message',group = 'Alert Message')
//plotting the vwap
if barstate.islast//confirmedhistory
if array.size(final_val)>0
for i=array.size(final_val)-1 to 0
line.new(bar_index[i+1],array.get(final_val,i),bar_index[i],array.get(final_val,i),color=color.red)
if ta.crossover(close, array.get(final_val,i))
alert(alertMH,freq = alert.freq_once_per_bar_close)
//label.new(bar_index,close,'TH')
if array.size(final_vallo)>0
for i=array.size(final_vallo)-1 to 0
line.new(bar_index[i+1],array.get(final_vallo,i),bar_index[i],array.get(final_vallo,i),color=color.lime)
if ta.crossunder(close, array.get(final_vallo,i))
alert(alertML,freq = alert.freq_once_per_bar_close)
//label.new(bar_index,close,'TL')
|
ICT MTF Order Block Wicks [MK] | https://www.tradingview.com/script/RFAvhAua-ICT-MTF-Order-Block-Wicks-MK/ | malk1903 | https://www.tradingview.com/u/malk1903/ | 362 | 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/
//@malk1903
//@version=5
indicator(title='ICT MTF Order Block Wicks [MK]', shorttitle = 'OB Wicks [MK]',overlay=true, max_boxes_count = 500, max_labels_count = 500)
grp_tfs_enabled = "ENABLED TIME FRAMES"
tfcstrg = "Order Block Fill Colors"
inSession = not na(time(timeframe.period, "0930-1600"))
display = true
//hover1 = input.bool(true,"Hover over (!) for information about FVG's",group = "IMPORTANT INFORMATION",tooltip = descTip1+descTip2+descTip3+descTip4+descTip5)
//hover2 = input.bool(true,"Hover over (!) for alert usage",group = "IMPORTANT INFORMATION",tooltip = alertTip1+alertTip2+alertTip3+alertTip4+alertTip5)
OnlyMktHrs = false
fmthds = "Body"
fvgmethod = fmthds == "Body" ? true : false
show_labels = true
show_timeonlabels = false
hoursOffsetInput = input.float(-5.0, "Timezone offset", minval = -12.0, maxval = 14.0, step = 0.5, group='', inline="0")
label_shift = input.int(defval=10, minval=1, maxval=100, step=1, title="OB Offset to Right", group = '', inline ='0')
var msOffsetInput = hoursOffsetInput * 1000 * 60 * 60
labelcolor = input.color(color.new(color.orange,0),"Label Colour",group = "",inline="1")
incursion_alerts = true
incursion_pct = 20
intrusion_percentage= incursion_pct / 100
mitiaction = "Normal"
mitigationaction = if (mitiaction == 'Normal')
1
else
if (mitiaction == 'Dynamic')
2
else
if (mitiaction == 'None')
3
else
4
nomiticolor = color.new(color.yellow,85)
nmc_trans = color.t(nomiticolor)
show_mitigated_text = false
mitig_type = "Wicks"
UseBodyForMitigation= mitig_type == "Body" ? true : false
entrychangecolor = input.bool(true,"Change OB Color On Entry ",inline='3')
entry_bull_color = input.color(color.new(color.white,90),"Bull",inline='3')
entry_bear_color = input.color(color.new(color.white,90),"Bear",inline='3')
// ============================================ //
// FVG Time Frame inputs and settings
// ============================================ //
enable_current_timeframe = false
enable_5min = input.bool(false,"5 Minute",group = grp_tfs_enabled,inline="0")
enable_10min = input.bool(true,"10 Minute",group = grp_tfs_enabled,inline="0")
enable_15min = input.bool(true,"15 Minute",group = grp_tfs_enabled,inline="0")
enable_30min = input.bool(true,"30 Minute",group = grp_tfs_enabled,inline="0")
enable_1hr = input.bool(true,"1 Hour",group = grp_tfs_enabled,inline="0")
enable_4hr = input.bool(false,"4 Hour",group = grp_tfs_enabled,inline="0")
enable_8hr = input.bool(false,"8 Hour",group = grp_tfs_enabled,inline="0")
enable_12hr = input.bool(false,"12 Hour",group = grp_tfs_enabled,inline="0")
enable_Daily = input.bool(false,"Daily",group = grp_tfs_enabled,inline="0")
enable_Week = input.bool(false,"Weekly",group = grp_tfs_enabled,inline="0")
enable_Month = input.bool(false,"Monthly",group = grp_tfs_enabled,inline="0")
current_timeframe = timeframe.period
var timestring = ""
if timeframe.isintraday
if str.tonumber(current_timeframe) > 59
timestring := str.tostring(str.tonumber(current_timeframe) / 60) + " Hr"
else
timestring := current_timeframe + " Min"
else if timeframe.isdaily
timestring := "Daily"
else if timeframe.isweekly
timestring := "Weekly"
else
timestring := "Monthly"
// ============================================ //
// FVG Supported Timeframe strings used for labels and alertcondition at end
// ============================================ //
currtfstring = timestring
maxgroup = "MAX OBs SETTINGS (COMBINED MAXIMUM MUST BE LESS THAN 500)"
curr_MaxArraySize = 8
MaxArraySize_5min = input.int(8,"5 Min",group = maxgroup,inline="0",minval = 1)
MaxArraySize_10min = input.int(8,"10 Min",group = maxgroup,inline="0",minval = 1)
MaxArraySize_15min = input.int(8,"15 Min",group = maxgroup,inline="0",minval = 1)
MaxArraySize_30min = input.int(8,"30 Min",group = maxgroup,inline="1",minval = 1)
MaxArraySize_1hr = input.int(8,"1 Hr",group = maxgroup,inline="1",minval = 1)
MaxArraySize_4hr = input.int(8,"4 Hr",group = maxgroup,inline="1",minval = 1)
MaxArraySize_8hr = input.int(8,"8 Hr",group = maxgroup,inline="2",minval = 1)
MaxArraySize_12hr = input.int(8,"12 Hr",group = maxgroup,inline="2",minval = 1)
MaxArraySize_Daily = input.int(8,"Daily",group = maxgroup,inline="2",minval = 1)
MaxArraySize_Wkly = input.int(8,"Weekly",group = maxgroup,inline="3",minval = 1)
MaxArraySize_Mthly = input.int(8,"Monthly",group = maxgroup,inline="3",minval = 1)
//Create error box template (as table) if user entered over 500 fvgs total
var table ErrorBox = table.new(position.bottom_right, 1, 1, frame_color=color.red,frame_width = 1)
tot_user_max_boxes = curr_MaxArraySize + MaxArraySize_5min + MaxArraySize_10min + MaxArraySize_15min + MaxArraySize_1hr + MaxArraySize_4hr + MaxArraySize_8hr + MaxArraySize_Daily + MaxArraySize_Wkly + MaxArraySize_Mthly
isError = tot_user_max_boxes > 500
if isError
table.cell(ErrorBox, 0, 0, "MTF OB INDICATOR ERROR\n\n"+"Max Number of OBs exceeded, please change settings.", bgcolor = color.new(color.blue, 50),
text_color = color.red,text_halign=text.align_center)
bgcolor=color.new(color.maroon,90)
// SET DEFAULT COLORS FOR ALL TIMEFRAMES
bullfvgcolor = input.color(color.new(color.yellow,80),"Bull OB Fill Color",group = tfcstrg,inline="0") //" "
bearfvgcolor = input.color(color.new(color.blue,80),"Bear OB Fill Color",group = tfcstrg,inline="0")
boxright = true
OBwick_extend = false
// FVG Box Border Inputs
box_border_bull_color = (color.new(color.yellow,100))
box_border_bear_color = (color.new(color.blue,100))
box_border_width = 1
bbstyle_string = "Solid"
box_border_style = line.style_dotted
//show_mts = input.bool(true,'Show OB Thresholds',group = 'mk test',inline="1")
// --------------------------------------------------------------- //
// | FUNCTIONS| //
// --------------------------------------------------------------- //
// simple strings required for request.security function in latter main code calls to handle_all function
_gettf_interval_str(simple int index) =>
string result = switch index
0 => "5"
1 => "10"
2 => "15"
3 => "30"
4 => "60"
5 => "240"
6 => "480"
7 => "720"
8 => "D"
9 => "W"
10 => "M"
=> "Unsupported Timeframe"
// simple strings require for label displays used in add_label ultimately
_gettf_label_str(simple int index) =>
string result = switch index
0 => "5 Min"
1 => "10 Min"
2 => "15 Min"
3 => "30 Min"
4 => "1 Hr"
5 => "4 Hr"
6 => "8 Hr"
7 => "12Hr"
8 => "Daily"
9 => "Weekly"
10 => "Monthly"
=> "Unsupported Timeframe"
// used if user selected use chart timeframe option to see not double work if chart is set to same timeframe as another enabled timeframe for fvg creation
_not_current_timeframe_equal_enabled_tfs(_current_timeframe) =>
result = switch _current_timeframe
"5" => not enable_5min
"10" => not enable_10min
"15" => not enable_15min
"30" => not enable_30min
"60" => not enable_1hr
"240" => not enable_4hr
"480" => not enable_8hr
"720" => not enable_12hr
"D" => not enable_Daily
"W" => not enable_Week
"M" => not enable_Month
=> true
// ************* SEE IF NEW BULL FVGs DETECTED
_isfvgbull(_fvgmethod,_open1,_close1,_open,_close,_high1,_low1) =>
if display
if _fvgmethod // if body fvg detection
_open1 > _close1 and _open < _close and _close > _high1
else // else wick detection
_open < _high1
else
false
// ************* SEE IF NEW BEAR FVGs DETECTED
_isfvgbear(_fvgmethod,_open1,_close1,_open,_close,_high1,_low1) =>
if display
if _fvgmethod
_open1 < _close1 and _open > _close and _close < _low1
else
_open < _low1
else
false
// *************** DELETE A BOX AND ASSOCIATED LABEL
_box_n_label_delete(_boxarray,_i,_labelarray,_labelflag) =>
bptr = array.get(_boxarray,_i)
box.delete(bptr)
array.remove(_boxarray, _i)
if _labelflag
lptr = array.get(_labelarray,_i)
label.delete(lptr)
array.remove(_labelarray,_i)
// *************** GET A FVG BOX TOP AND BOTTOM VALUES
_getboxelements(_boxptr,_i) =>
_boxelement = array.get(_boxptr,_i)
_left = box.get_left(_boxelement)
_top = box.get_top(_boxelement)
_btm = box.get_bottom(_boxelement)
_right = box.get_right(_boxelement)
[_boxelement,_left,_top,_btm,_right]
// ************** GET LEFT SIDE START BAR INDEX OF EXISTING BOX, for use in preventing duplicates for higher timeframes
_getboxstart(_boxptr,_i) =>
_boxelement = array.get(_boxptr,_i)
// *************** ADD A LABEL TO AN FVG
_addlabel(_fvglabelsarray,_bar_index,_high,_string,_style,y,_show_label) =>
var string s = na
if _show_label
if show_timeonlabels
s := _string + str.format(" {0,date,HH:mm MM/dd/yy}", time + msOffsetInput)
else
s := _string
blabel = label.new(_bar_index,_high,text=s,color=color.rgb(0,0,0,100),style = _style) //_string,color=color.rgb(0,0,0,100),style = _style)
label.set_textcolor(blabel,labelcolor)//color.rgb(label_red,label_grn,label_blu,label_trans))
label.set_xy(blabel,_bar_index + label_shift,y)
label.set_size(blabel,size.normal)
array.push(_fvglabelsarray,blabel)
// added these two globally as can't use them in functions with consistency/reliability towards incursion alerts
lasthigh = high[1]
lastlow = low[1]
// compare existing bull fvg box values to current price action
_getbullfvgaction(_top,_bottom,_intrusion_percentage) =>
midpt = (_top + _bottom) / 2
threshold = _top - (_intrusion_percentage * (_top - _bottom))
_have_intrusion = low < threshold and lastlow > threshold
_lowundertop = low < _top
_lowunderbtm = low < _bottom
_lowundermid = low < midpt
_closeundertop = close < _top
_closeunderbtm = close < _bottom
_closeundermid = low < midpt
[_lowundertop,_lowunderbtm,_closeundertop,_closeunderbtm,_lowundermid,_closeundermid,_have_intrusion]//,_closecrosswithin]
// compare existing bear fvg box values to current price action
_getbearfvgaction(_top,_bottom,_intrusion_percentage) =>
midpt = (_top + _bottom) / 2
threshold = _bottom + (_intrusion_percentage * (_top - _bottom))
_have_intrusion = high > threshold and lasthigh < threshold
_highovertop = high > _top
_highoverbtm = high > _bottom
_highovermid = high > midpt
_closeovertop = close > _top
_closeoverbtm = close > _bottom
_closeovermid = close > midpt
[_highovertop,_highoverbtm,_closeovertop,_closeoverbtm,_highovermid,_closeovermid,_have_intrusion]
// used for adjusting fvg label position with each new bar
_setlabelxy(_fvglabels,_i,_barindex,_top,_bottom) =>
_lptr = array.get(_fvglabels,_i)
label.set_xy(_lptr,_barindex + label_shift,(_top + _bottom) / 2)
// used for adjusting bull box position with each new bar
_setboxleftbull(_boxbull,_i,_barindex) =>
_bxbull = box.get_left(_boxbull)
box.set_left(_boxbull,last_bar_index + label_shift)
// used for adjusting bear box position with each new bar
_setboxleftbear(_boxbear,_i,_barindex) =>
_bxbear = box.get_left(_boxbear)
box.set_left(_boxbear,last_bar_index + label_shift)
// get higher timeframe price values
_gethighlowcloseopens(_ticker,_period,_high,_high2,_low,_low2,_close1,_open1) =>
request.security(_ticker,_period,[_high,_high2,_low,_low2,_close1,_open1])
// modify existing bull fvg boxes for incursion, deletion etc.
_update_bull_fvgs(_boxbull,_labelsbull,_timestring) =>
for i = array.size(_boxbull) - 1 to 0 by 1
[fvgboxbull,left,top,bottom,right] = _getboxelements(_boxbull,i)
[lowundertop,lowunderbtm,closeundertop,closeunderbtm,lowundermid,closeundermid,intrusion] = _getbullfvgaction(top,bottom,intrusion_percentage)
// INCURSION ALERT DONE HERE: if mitigation action is normal or none then do alert
if (mitigationaction == 1 or mitigationaction == 3) and intrusion and incursion_alerts
alert("Bull OB Wick Incursion " + str.tostring(_timestring), alert.freq_once_per_bar)
if entrychangecolor
if lowundertop // low < top
box.set_bgcolor(fvgboxbull,entry_bull_color)
if show_labels
_setlabelxy(_labelsbull,i,bar_index,top,bottom)
_setboxleftbull(fvgboxbull,i,bar_index)
// *** if mitigation is set to dynamic and body is referenced with price and price is within fvg
if mitigationaction == 2 and UseBodyForMitigation and closeundertop
box.set_top(fvgboxbull,close)
if show_labels
_setlabelxy(_labelsbull,i,bar_index,close,bottom)
else
// else if mitigation set to dynamic and body mitigation NOT enabled and btm wick goes below top of fvg band then move band top lower
if mitigationaction == 2 and lowundertop
box.set_top(fvgboxbull,low)
if show_labels
_setlabelxy(_labelsbull,i,bar_index,low,bottom)
// section to delete boxes when fvg filled
if mitigationaction == 3 // if 'none' selected for mitigation
if UseBodyForMitigation and closeunderbtm
box.set_bgcolor(fvgboxbull,color.new(nomiticolor,nmc_trans))
else
if lowunderbtm
box.set_bgcolor(fvgboxbull,color.new(nomiticolor,nmc_trans))
if (UseBodyForMitigation and closeunderbtm) or lowunderbtm
if show_labels and show_mitigated_text
larray = array.get(_labelsbull,i)
curr_text = label.get_text(larray)
found = str.contains(curr_text,"Mitigated")
if not found
label.set_text(larray,curr_text + " Mitigated")
if mitigationaction == 1 or mitigationaction == 2
if UseBodyForMitigation and closeunderbtm
_box_n_label_delete(_boxbull, i,_labelsbull, show_labels)
else
if lowunderbtm
_box_n_label_delete(_boxbull, i,_labelsbull, show_labels)
if mitigationaction == 4 // if half mitigation
if UseBodyForMitigation and closeundermid
_box_n_label_delete(_boxbull, i,_labelsbull, show_labels)
else
if lowundermid
_box_n_label_delete(_boxbull, i,_labelsbull, show_labels)
// modify existing bear fvg boxes for incursion, deletion etc.
_update_bear_fvgs(_boxbear,_labelsbear,_timestring) =>
for i = array.size(_boxbear) - 1 to 0 by 1
[fvgboxbear,left,top,bottom,right] = _getboxelements(_boxbear,i)
[highovertop,highoverbtm,closeovertop,closeoverbtm,highovermid,closeovermid,intrusion] = _getbearfvgaction(top,bottom,intrusion_percentage)
// INCURSION ALERT DONE HERE: if mitigation action is normal or none then do alert
if (mitigationaction == 1 or mitigationaction == 3) and intrusion and incursion_alerts
alert("Bear OB Wick Incursion " + str.tostring(_timestring), alert.freq_once_per_bar)
if entrychangecolor
if highoverbtm
box.set_bgcolor(fvgboxbear,entry_bear_color)//color.new(bearfvgcolor,_bear_trans - (_bear_trans / 4)))
else
box.set_bgcolor(fvgboxbear,bearfvgcolor)//color.new(bearfvgcolor,_bear_trans))
if show_labels
_setlabelxy(_labelsbear,i,bar_index,top,bottom)
_setboxleftbear(fvgboxbear,i,bar_index)
// *** if mitigation is set to dynamic and body is referenced with price and price is within fvg
if mitigationaction == 2 and UseBodyForMitigation and closeoverbtm
box.set_bottom(fvgboxbear,close)
if show_labels
_setlabelxy(_labelsbear,i,bar_index,close,bottom)
else
// else if mitigation set to dynamic and body mitigation NOT enabled and top wick goes above bottom of fvg band then move band bottom up
if mitigationaction == 2 and highoverbtm
box.set_bottom(fvgboxbear,high)
if show_labels
_setlabelxy(_labelsbear,i,bar_index,top,high)
if mitigationaction == 3 // if 'none' selected for mitigation
if UseBodyForMitigation and closeovertop
box.set_bgcolor(fvgboxbear,color.new(nomiticolor,nmc_trans))
else
if highovertop
box.set_bgcolor(fvgboxbear,color.new(nomiticolor,nmc_trans))
if (UseBodyForMitigation and closeovertop) or highovertop
if show_labels and show_mitigated_text
larray = array.get(_labelsbear,i)
curr_text = label.get_text(larray)
found = str.contains(curr_text,"Mitigated")
if not found
label.set_text(larray,curr_text + " Mitigated")
if mitigationaction == 1 or mitigationaction == 2
if UseBodyForMitigation and closeovertop
_box_n_label_delete(_boxbear, i,_labelsbear, show_labels)
else
if highovertop
_box_n_label_delete(_boxbear, i,_labelsbear, show_labels)
if mitigationaction == 4 // if half mitigation
if UseBodyForMitigation and closeovermid
_box_n_label_delete(_boxbear, i,_labelsbear, show_labels)
else
if highovermid
_box_n_label_delete(_boxbear, i,_labelsbear, show_labels)
// check for duplicate boxes required for eliminating duplicate higher timeframe fvg boxes, input 1: pointer to box array, input 2: bar_index which is left side of box in bar_index number
_duplicate_box(_boxarray,_top,_bottom) =>
found = false
if array.size(_boxarray) > 0
for i = array.size(_boxarray) - 1 to 0 by 1
[_barray,left,top,bottom,right] = _getboxelements(_boxarray,i)
if _top == top //and _bottom == bottom //_left_bar_index == left
found := true
break
found
// main function call here - detects and calls to create fvg boxes then calls the update fvg functions for bulls and bears fvgs for already existing fvg boxes
_handle_all(_tstring,_bullfvgs,_bearfvgs,_bulllabels,_bearlabels,_maxarraysize,_open1,_close1,_open,_close,_high1,_low1) =>
var bool _newBull = false
var bool _newBear = false
if OnlyMktHrs and inSession or not OnlyMktHrs
_newBull := _isfvgbull(fvgmethod,_open1,_close1,_open,_close,_high1,_low1)
_newBear := _isfvgbear(fvgmethod,_open1,_close1,_open,_close,_high1,_low1)
//_fvgmethod,_open1,_close1,_open,_close,_high1,_low1 - MIGHT HAVE to take _ out before FVG method
if _newBull
if array.size(_bullfvgs) > _maxarraysize
_box_n_label_delete(_bullfvgs, 0,_bulllabels, show_labels)
if not _duplicate_box(_bullfvgs,_high1,_open1) // inputs top, bottom of box
array.push(_bullfvgs, box.new(left=last_bar_index + 20, bottom=_open1, right=last_bar_index + 200, top=_high1, bgcolor=bullfvgcolor, border_color=box_border_bull_color, border_width = box_border_width, border_style = box_border_style, extend=extend.right))
//if OBwick_extend
//box.set_right(_bullfvgs, bar_index)
if show_labels
_addlabel(_bulllabels,bar_index,_high1,_tstring + " OB BULL",label.style_label_left,(_high1[1] + _low1) / 2, show_labels)
if _newBear
if array.size(_bearfvgs) > _maxarraysize
_box_n_label_delete(_bearfvgs, 0,_bearlabels, show_labels)
if not _duplicate_box(_bearfvgs,_open1,_low1) // inputs top, bottom of box
array.push(_bearfvgs, box.new(left=last_bar_index + 20, top=_open1, right=last_bar_index + 200, bottom=_low1, bgcolor=bearfvgcolor, border_color=box_border_bear_color, border_width = box_border_width, border_style = box_border_style, extend=extend.right))
//if OBwick_extend
//box.set_right(_bearfvgs, bar_index)
if show_labels
_addlabel(_bearlabels,bar_index,_high1,_tstring + " OB BEAR",label.style_label_left,(_high1[1] + _low1) / 2, show_labels)
//| BULL FVG HANDLING AREA | //
// ----------------------------------------------- //
if array.size(_bullfvgs) > 0 // this code is to handle incursion alerts before FVG's possibly being mitigated
_update_bull_fvgs(_bullfvgs,_bulllabels,_tstring)
// ----------------------------------------------- //
// | BEAR FVG HANDLING AREA | //
// ----------------------------------------------- //
if array.size(_bearfvgs) > 0 // this code is to handle incursion alerts before FVG's possibly being mitigated
_update_bear_fvgs(_bearfvgs,_bearlabels,_tstring)
[_newBull,_newBear]
// ***************************************************
// Array and Box definition area
// ***************************************************
var box[] fvgboxBull = array.new_box()
var box[] fvgboxBear = array.new_box()
var fvglabelsBull = array.new_label()
var fvglabelsBear = array.new_label()
var bool newboxBull = false
var bool newboxBear = false
var box[] fvgboxBull5 = array.new_box()
var box[] fvgboxBear5 = array.new_box()
var fvglabelsBull5 = array.new_label()
var fvglabelsBear5 = array.new_label()
var bool newboxBull5 = false
var bool newboxBear5 = false
var box[] fvgboxBull10 = array.new_box()
var box[] fvgboxBear10 = array.new_box()
var fvglabelsBull10 = array.new_label()
var fvglabelsBear10 = array.new_label()
var bool newboxBull10 = false
var bool newboxBear10 = false
var box[] fvgboxBull15 = array.new_box()
var box[] fvgboxBear15 = array.new_box()
var fvglabelsBull15 = array.new_label()
var fvglabelsBear15 = array.new_label()
var bool newboxBull15 = false
var bool newboxBear15 = false
var box[] fvgboxBull30 = array.new_box()
var box[] fvgboxBear30 = array.new_box()
var fvglabelsBull30 = array.new_label()
var fvglabelsBear30 = array.new_label()
var bool newboxBull30 = false
var bool newboxBear30 = false
var box[] fvgboxBull1hr = array.new_box()
var box[] fvgboxBear1hr = array.new_box()
var fvglabelsBull1hr= array.new_label()
var fvglabelsBear1hr= array.new_label()
var bool newboxBull1hr = false
var bool newboxBear1hr = false
var box[] fvgboxBull4hr = array.new_box()
var box[] fvgboxBear4hr = array.new_box()
var fvglabelsBull4hr= array.new_label()
var fvglabelsBear4hr= array.new_label()
var bool newboxBull4hr = false
var bool newboxBear4hr = false
var box[] fvgboxBull8hr = array.new_box()
var box[] fvgboxBear8hr = array.new_box()
var bool newboxBull8hr = false
var bool newboxBear8hr = false
var fvglabelsBull8hr= array.new_label()
var fvglabelsBear8hr= array.new_label()
var box[] fvgboxBull12hr = array.new_box()
var box[] fvgboxBear12hr = array.new_box()
var bool newboxBull12hr = false
var bool newboxBear12hr = false
var fvglabelsBull12hr= array.new_label()
var fvglabelsBear12hr= array.new_label()
var box[] fvgboxBullDaily = array.new_box()
var box[] fvgboxBearDaily = array.new_box()
var fvglabelsBullDaily = array.new_label()
var fvglabelsBearDaily = array.new_label()
var bool newboxBullDaily = false
var bool newboxBearDaily = false
var box[] fvgboxBullWeekly = array.new_box()
var box[] fvgboxBearWeekly = array.new_box()
var fvglabelsBullWeekly = array.new_label()
var fvglabelsBearWeekly = array.new_label()
var bool newboxBullWeekly = false
var bool newboxBearWeekly = false
var box[] fvgboxBullMonthly = array.new_box()
var box[] fvgboxBearMonthly = array.new_box()
var fvglabelsBullMonthly = array.new_label()
var fvglabelsBearMonthly = array.new_label()
var bool newboxBullMonthly = false
var bool newboxBearMonthly = false
///////////////////////////////////////
//| MAIN CODE |
///////////////////////////////////////
if enable_current_timeframe and _not_current_timeframe_equal_enabled_tfs(current_timeframe)
[_open1,_close1,_open,_close,_high1,_low1] = _gethighlowcloseopens(syminfo.tickerid,current_timeframe,open[1],close[1],open[0],close[0],high[1],low[1])
[tnewboxBull,tnewboxBear] = _handle_all(currtfstring,fvgboxBull,fvgboxBear,fvglabelsBull,fvglabelsBear,curr_MaxArraySize,_open1,_close1,_open,_close,_high1,_low1)
newboxBull := tnewboxBull
newboxBear := tnewboxBear
if enable_5min
[_open1,_close1,_open,_close,_high1,_low1] = _gethighlowcloseopens(syminfo.tickerid,_gettf_interval_str(0),open[1],close[1],open[0],close[0],high[1],low[1])
[tnewboxBull5,tnewboxBear5] =_handle_all(_gettf_label_str(0),fvgboxBull5,fvgboxBear5,fvglabelsBull5,fvglabelsBear5,MaxArraySize_5min,_open1,_close1,_open,_close,_high1,_low1)
newboxBull5 := tnewboxBull5
newboxBear5 := tnewboxBear5
if enable_10min
[_open1,_close1,_open,_close,_high1,_low1] = _gethighlowcloseopens(syminfo.tickerid,_gettf_interval_str(1),open[1],close[1],open[0],close[0],high[1],low[1])
[tnewboxBull10,tnewboxBear10] = _handle_all(_gettf_label_str(1),fvgboxBull10,fvgboxBear10,fvglabelsBull10,fvglabelsBear10,MaxArraySize_10min,_open1,_close1,_open,_close,_high1,_low1)
newboxBull10 := tnewboxBull10
newboxBear10 := tnewboxBear10
if enable_15min
[_open1,_close1,_open,_close,_high1,_low1] = _gethighlowcloseopens(syminfo.tickerid,_gettf_interval_str(2),open[1],close[1],open[0],close[0],high[1],low[1])
[tnewboxBull15,tnewboxBear15] = _handle_all(_gettf_label_str(2),fvgboxBull15,fvgboxBear15,fvglabelsBull15,fvglabelsBear15,MaxArraySize_15min,_open1,_close1,_open,_close,_high1,_low1)
newboxBull15 := tnewboxBull15
newboxBear15 := tnewboxBear15
if enable_30min
[_open1,_close1,_open,_close,_high1,_low1] = _gethighlowcloseopens(syminfo.tickerid,_gettf_interval_str(3),open[1],close[1],open[0],close[0],high[1],low[1])
[tnewboxBull30,tnewboxBear30] = _handle_all(_gettf_label_str(3),fvgboxBull30,fvgboxBear30,fvglabelsBull30,fvglabelsBear30,MaxArraySize_30min,_open1,_close1,_open,_close,_high1,_low1)
newboxBull30 := tnewboxBull30
newboxBear30 := tnewboxBear30
if enable_1hr
[_open1,_close1,_open,_close,_high1,_low1] = _gethighlowcloseopens(syminfo.tickerid,_gettf_interval_str(4),open[1],close[1],open[0],close[0],high[1],low[1])
[tnewboxBull1hr,tnewboxBear1hr] = _handle_all(_gettf_label_str(4),fvgboxBull1hr,fvgboxBear1hr,fvglabelsBull1hr,fvglabelsBear1hr,MaxArraySize_1hr,_open1,_close1,_open,_close,_high1,_low1)
newboxBull1hr := tnewboxBull1hr
newboxBear1hr := tnewboxBear1hr
if enable_4hr
[_open1,_close1,_open,_close,_high1,_low1] = _gethighlowcloseopens(syminfo.tickerid,_gettf_interval_str(5),open[1],close[1],open[0],close[0],high[1],low[1])
[tnewboxBull4hr,tnewboxBear4hr] = _handle_all(_gettf_label_str(5),fvgboxBull4hr,fvgboxBear4hr,fvglabelsBull4hr,fvglabelsBear4hr,MaxArraySize_4hr,_open1,_close1,_open,_close,_high1,_low1)
newboxBull4hr := tnewboxBull4hr
newboxBear4hr := tnewboxBear4hr
if enable_8hr
[_open1,_close1,_open,_close,_high1,_low1] = _gethighlowcloseopens(syminfo.tickerid,_gettf_interval_str(6),open[1],close[1],open[0],close[0],high[1],low[1])
[tnewboxBull8hr,tnewboxBear8hr] = _handle_all(_gettf_label_str(6),fvgboxBull8hr,fvgboxBear8hr,fvglabelsBull8hr,fvglabelsBear8hr,MaxArraySize_8hr,_open1,_close1,_open,_close,_high1,_low1)
newboxBull8hr := tnewboxBull8hr
newboxBear8hr := tnewboxBear8hr
if enable_12hr
[_open1,_close1,_open,_close,_high1,_low1] = _gethighlowcloseopens(syminfo.tickerid,_gettf_interval_str(7),open[1],close[1],open[0],close[0],high[1],low[1])
[tnewboxBull12hr,tnewboxBear12hr] = _handle_all(_gettf_label_str(7),fvgboxBull12hr,fvgboxBear12hr,fvglabelsBull12hr,fvglabelsBear12hr,MaxArraySize_12hr,_open1,_close1,_open,_close,_high1,_low1)
newboxBull12hr := tnewboxBull12hr
newboxBear12hr := tnewboxBear12hr
if enable_Daily
[_open1,_close1,_open,_close,_high1,_low1] = _gethighlowcloseopens(syminfo.tickerid,_gettf_interval_str(8),open[1],close[1],open[0],close[0],high[1],low[1])
[tnewboxBullDaily,tnewboxBearDaily] = _handle_all(_gettf_label_str(8),fvgboxBullDaily,fvgboxBearDaily,fvglabelsBullDaily,fvglabelsBearDaily,MaxArraySize_Daily,_open1,_close1,_open,_close,_high1,_low1)
newboxBullDaily := tnewboxBullDaily
newboxBearDaily := tnewboxBearDaily
if enable_Week
[_open1,_close1,_open,_close,_high1,_low1] = _gethighlowcloseopens(syminfo.tickerid,_gettf_interval_str(9),open[1],close[1],open[0],close[0],high[1],low[1])
[tnewboxBullWeekly,tnewboxBearWeekly] = _handle_all(_gettf_label_str(9),fvgboxBullWeekly,fvgboxBearWeekly,fvglabelsBullWeekly,fvglabelsBearWeekly,MaxArraySize_Wkly,_open1,_close1,_open,_close,_high1,_low1)
newboxBullWeekly := tnewboxBullWeekly
newboxBearWeekly := tnewboxBearWeekly
if enable_Month
[_open1,_close1,_open,_close,_high1,_low1] = _gethighlowcloseopens(syminfo.tickerid,_gettf_interval_str(10),open[1],close[1],open[0],close[0],high[1],low[1])
[tnewboxBullMonthly,tnewboxBearMonthly] = _handle_all(_gettf_label_str(10),fvgboxBullMonthly,fvgboxBearMonthly,fvglabelsBullMonthly,fvglabelsBearMonthly,MaxArraySize_Mthly,_open1,_close1,_open,_close,_high1,_low1)
newboxBullMonthly := tnewboxBullMonthly
newboxBearMonthly := tnewboxBearMonthly
// // ------------------------------------------------------- //
// // | STANDARD CONDITIONAL ALERT SECTION | //
// // ------------------------------------------------------- //
bull_fvg_creation_alert = newboxBull or newboxBull5 or newboxBull10 or newboxBull15 or newboxBull1hr or newboxBull4hr or newboxBull8hr or newboxBullDaily or newboxBullWeekly or newboxBullMonthly
alertcondition(bull_fvg_creation_alert,title='Bull OB Creation',message = 'Bull OB Creation' )
bear_fvg_creation_alert = newboxBear or newboxBear5 or newboxBear10 or newboxBear15 or newboxBear1hr or newboxBear4hr or newboxBear8hr or newboxBearDaily or newboxBearWeekly or newboxBearMonthly
alertcondition(bear_fvg_creation_alert,title='Bear OB Creation',message = 'Bear OB Creation' )
both_fvg_creation_alert = newboxBull or newboxBull5 or newboxBull10 or newboxBull15 or newboxBull1hr or newboxBull4hr or newboxBull8hr or newboxBullDaily or newboxBullWeekly or newboxBullMonthly or newboxBear or newboxBear5 or newboxBear10 or newboxBear15 or newboxBear1hr or newboxBear4hr or newboxBear8hr or newboxBearDaily or newboxBearWeekly or newboxBearMonthly
alertcondition(both_fvg_creation_alert,title='Bull or Bear OB Creation',message = 'Bull or Bear OB Creation' )
|
Futures All List Candle Analysis - FALCA | https://www.tradingview.com/script/wNrBPCCH/ | gokhanpirnal | https://www.tradingview.com/u/gokhanpirnal/ | 35 | 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/
// © gokhanpirnal
//@version=5
indicator("Futures All List Candle Analysis", shorttitle = "FALCA", overlay = false)
// | INPUT |
// Sorting
sortTable = input.string(title="Sort Table by" , defval="High-Low C/H",
options=[ "Alphabet", "High-Low C/H", "Low-High C/H", "High-Low C/O", "Low-High C/O", "High-Low C/L", "Low-High C/L"])
// Set Type
set = input.string(title="Sector Set Type" , defval="1.LIST",
options = ["1.LIST", "2.LIST", "3.LIST", "4.LIST", "5.LIST", "6.LIST", "7.LIST", "8.LIST", "9.LIST", "10.LIST", "11.LIST", "12.LIST", "FAVORITE LIST"])
// Table Position
in_table_pos = input.string(title="Table Location", defval= "Top Right",
options = [ "Top Right" , "Middle Right" , "Bottom Right" ,
"Top Center", "Middle Center", "Bottom Center",
"Top Left" , "Middle Left" , "Bottom Left" ],
group= "Table Styling")
// Table Size
in_table_size = input.string(title="Table Size", defval="Tiny",
options=["Auto", "Huge", "Large", "Normal", "Small", "Tiny"],
group= "Table Styling")
// Table Colors
cell_lowColor = input.color(color.red, title= "Low Cell",
inline="1", group="TableColor")
cell_midColor = input.color(color.yellow, title= "Mid Cell",
inline="2", group="TableColor")
cell_highColor = input.color(color.green, title= "High Cell",
inline="3", group="TableColor")
background_col = input.color(color.gray, title= "Background Color",
inline="1", group="TableColor")
title_textCol = input.color(color.white, title="Title Text Color",
inline="2", group="TableColor")
cell_textCol = input.color(color.black, title="Cell Text Color",
inline="3", group="TableColor")
// | SYMBOLS |
sym_short(s) =>
str.substring(s, str.pos(s, ":") + 1)
symbol(num, req) =>
if req == "symbols"
if set == "1.LIST"
symbols = num == 0 ? "BINANCE:1000LUNCUSDTPERP" : num == 1 ? "BINANCE:1000SHIBUSDTPERP" :
num == 2 ? "BINANCE:1000XECUSDTPERP" : num == 3 ? "BINANCE:1INCHUSDTPERP" :
num == 4 ? "BINANCE:AAVEUSDTPERP" : num == 5 ? "BINANCE:ADAUSDTPERP" :
num == 6 ? "BINANCE:ALGOUSDTPERP" : num == 7 ? "BINANCE:ALICEUSDTPERP" :
num == 8 ? "BINANCE:ALPHAUSDTPERP" : num == 9 ? "BINANCE:ANKRUSDTPERP" :
num == 10 ? "BINANCE:ANTUSDTPERP" : num == 11 ? "BINANCE:APEUSDTPERP" :
num == 12 ? "BINANCE:API3USDTPERP" : na
else if set == "2.LIST"
symbols = num == 0 ? "BINANCE:APTUSDTPERP" : num == 1 ? "BINANCE:ARPAUSDTPERP" :
num == 2 ? "BINANCE:ARUSDTPERP" : num == 3 ? "BINANCE:ATAUSDTPERP" :
num == 4 ? "BINANCE:ATOMUSDTPERP" : num == 5 ? "BINANCE:AUDIOUSDTPERP" :
num == 6 ? "BINANCE:AVAXUSDTPERP" : num == 7 ? "BINANCE:AXSUSDTPERP" :
num == 8 ? "BINANCE:BAKEUSDTPERP" : num == 9 ? "BINANCE:BALUSDTPERP" :
num == 10 ? "BINANCE:BANDUSDTPERP" : num == 11 ? "BINANCE:BATUSDTPERP" :
num == 12 ? "BINANCE:BCHUSDTPERP" : na
else if set == "3.LIST"
symbols = num == 0 ? "BINANCE:BELUSDTPERP" : num == 1 ? "BINANCE:BLUEBIRDUSDTPERP" :
num == 2 ? "BINANCE:BLZUSDTPERP" : num == 3 ? "BINANCE:BNBUSDTPERP" :
num == 4 ? "BINANCE:BNXUSDTPERP" : num == 5 ? "BINANCE:BTCDOMUSDTPERP" :
num == 6 ? "BINANCE:BTCUSDTPERP" : num == 7 ? "BINANCE:C98USDTPERP" :
num == 8 ? "BINANCE:CELOUSDTPERP" : num == 9 ? "BINANCE:CELRUSDTPERP" :
num == 10 ? "BINANCE:CHRUSDTPERP" : num == 11 ? "BINANCE:CHZUSDTPERP" :
num == 12 ? "BINANCE:COMPUSDTPERP" : na
else if set == "4.LIST"
symbols = num == 0 ? "BINANCE:COTIUSDTPERP" : num == 1 ? "BINANCE:CRVUSDTPERP" :
num == 2 ? "BINANCE:CTKUSDTPERP" : num == 3 ? "BINANCE:CTSIUSDTPERP" :
num == 4 ? "BINANCE:CVXUSDTPERP" : num == 5 ? "BINANCE:DARUSDTPERP" :
num == 6 ? "BINANCE:DASHUSDTPERP" : num == 7 ? "BINANCE:DEFIUSDTPERP" :
num == 8 ? "BINANCE:DENTUSDTPERP" : num == 9 ? "BINANCE:DGBUSDTPERP" :
num == 10 ? "BINANCE:DOGEUSDTPERP" : num == 11 ? "BINANCE:DOTUSDTPERP" :
num == 12 ? "BINANCE:DUSKUSDTPERP" : na
else if set == "5.LIST"
symbols = num == 0 ? "BINANCE:DYDXUSDTPERP" : num == 1 ? "BINANCE:EGLDUSDTPERP" :
num == 2 ? "BINANCE:ENJUSDTPERP" : num == 3 ? "BINANCE:ENSUSDTPERP" :
num == 4 ? "BINANCE:EOSUSDTPERP" : num == 5 ? "BINANCE:ETCUSDTPERP" :
num == 6 ? "BINANCE:ETHUSDTPERP" : num == 7 ? "BINANCE:FILUSDTPERP" :
num == 8 ? "BINANCE:FLMUSDTPERP" : num == 9 ? "BINANCE:FLOWUSDTPERP" :
num == 10 ? "BINANCE:FOOTBALLUSDTPERP" : num == 11 ? "BINANCE:FTMUSDTPERP" :
num == 12 ? "BINANCE:GALAUSDTPERP" : na
else if set == "6.LIST"
symbols = num == 0 ? "BINANCE:GMTUSDTPERP" : num == 1 ? "BINANCE:GRTUSDTPERP" :
num == 2 ? "BINANCE:GTCUSDTPERP" : num == 3 ? "BINANCE:HBARUSDTPERP" :
num == 4 ? "BINANCE:HNTUSDTPERP" : num == 5 ? "BINANCE:HOTUSDTPERP" :
num == 6 ? "BINANCE:ICPUSDTPERP" : num == 7 ? "BINANCE:ICXUSDTPERP" :
num == 8 ? "BINANCE:IMXUSDTPERP" : num == 9 ? "BINANCE:INJUSDTPERP" :
num == 10 ? "BINANCE:IOSTUSDTPERP" : num == 11 ? "BINANCE:IOTAUSDTPERP" :
num == 12 ? "BINANCE:IOTXUSDTPERP" : na
else if set == "7.LIST"
symbols = num == 0 ? "BINANCE:JASMYUSDTPERP" : num == 1 ? "BINANCE:KAVAUSDTPERP" :
num == 2 ? "BINANCE:KLAYUSDTPERP" : num == 3 ? "BINANCE:KNCUSDTPERP" :
num == 4 ? "BINANCE:KSMUSDTPERP" : num == 5 ? "BINANCE:LDOUSDTPERP" :
num == 6 ? "BINANCE:LINAUSDTPERP" : num == 7 ? "BINANCE:LINKUSDTPERP" :
num == 8 ? "BINANCE:LITUSDTPERP" : num == 9 ? "BINANCE:LPTUSDTPERP" :
num == 10 ? "BINANCE:LRCUSDTPERP" : num == 11 ? "BINANCE:LTCUSDTPERP" :
num == 12 ? "BINANCE:LUNA2USDTPERP" : na
else if set == "8.LIST"
symbols = num == 0 ? "BINANCE:MANAUSDTPERP" : num == 1 ? "BINANCE:MASKUSDTPERP" :
num == 2 ? "BINANCE:MATICUSDTPERP" : num == 3 ? "BINANCE:MKRUSDTPERP" :
num == 4 ? "BINANCE:MTLUSDTPERP" : num == 5 ? "BINANCE:NEARUSDTPERP" :
num == 6 ? "BINANCE:NEOUSDTPERP" : num == 7 ? "BINANCE:NKNUSDTPERP" :
num == 8 ? "BINANCE:OCEANUSDTPERP" : num == 9 ? "BINANCE:OGNUSDTPERP" :
num == 10 ? "BINANCE:OMGUSDTPERP" : num == 11 ? "BINANCE:ONEUSDTPERP" :
num == 12 ? "BINANCE:ONTUSDTPERP" : na
else if set == "9.LIST"
symbols = num == 0 ? "BINANCE:OPUSDTPERP" : num == 1 ? "BINANCE:PEOPLEUSDTPERP" :
num == 2 ? "BINANCE:QNTUSDTPERP" : num == 3 ? "BINANCE:QTUMUSDTPERP" :
num == 4 ? "BINANCE:REEFUSDTPERP" : num == 5 ? "BINANCE:RENUSDTPERP" :
num == 6 ? "BINANCE:RLCUSDTPERP" : num == 7 ? "BINANCE:ROSEUSDTPERP" :
num == 8 ? "BINANCE:RSRUSDTPERP" : num == 9 ? "BINANCE:RUNEUSDTPERP" :
num == 10 ? "BINANCE:RVNUSDTPERP" : num == 11 ? "BINANCE:SANDUSDTPERP" :
num == 12 ? "BINANCE:SFPUSDTPERP" : na
else if set == "10.LIST"
symbols = num == 0 ? "BINANCE:SKLUSDTPERP" : num == 1 ? "BINANCE:SNXUSDTPERP" :
num == 2 ? "BINANCE:SOLUSDTPERP" : num == 3 ? "BINANCE:SPELLUSDTPERP" :
num == 4 ? "BINANCE:STGUSDTPERP" : num == 5 ? "BINANCE:STMXUSDTPERP" :
num == 6 ? "BINANCE:STORJUSDTPERP" : num == 7 ? "BINANCE:SUSHIUSDTPERP" :
num == 8 ? "BINANCE:SXPUSDTPERP" : num == 9 ? "BINANCE:THETAUSDTPERP" :
num == 10 ? "BINANCE:TOMOUSDTPERP" : num == 11 ? "BINANCE:TRBUSDTPERP" :
num == 12 ? "BINANCE:TRXUSDTPERP" : na
else if set == "11.LIST"
symbols = num == 0 ? "BINANCE:UNFIUSDTPERP" : num == 1 ? "BINANCE:UNIUSDTPERP" :
num == 2 ? "BINANCE:VETUSDTPERP" : num == 3 ? "BINANCE:WAVESUSDTPERP" :
num == 4 ? "BINANCE:WOOUSDTPERP" : num == 5 ? "BINANCE:XEMUSDTPERP" :
num == 6 ? "BINANCE:XLMUSDTPERP" : num == 7 ? "BINANCE:XMRUSDTPERP" :
num == 8 ? "BINANCE:XRPUSDTPERP" : num == 9 ? "BINANCE:XTZUSDTPERP" :
num == 10 ? "BINANCE:YFIUSDTPERP" : num == 11 ? "BINANCE:ZECUSDTPERP" :
num == 12 ? "BINANCE:ZENUSDTPERP" : na
else if set == "12.LIST"
symbols = num == 0 ? "BINANCE:ZILUSDTPERP" : num == 1 ? "BINANCE:ZRXUSDTPERP" :
num == 2 ? "CRYPTOCAP:TOTAL" : na
else if set == "FAVORITE LIST"
symbols = num == 0 ? "CRYPTOCAP:TOTAL" : num == 1 ? "BINANCE:BTCUSDTPERP" :
num == 2 ? "BINANCE:BTCDOMUSDTPERP" : num == 3 ? input.symbol(defval="BINANCE"):
num == 4 ? input.symbol(defval="BINANCE"): num == 5 ? input.symbol(defval="BINANCE"):
num == 6 ? input.symbol(defval="BINANCE"): num == 7 ? input.symbol(defval="BINANCE"):
num == 8 ? input.symbol(defval="BINANCE"): num == 9 ? input.symbol(defval="BINANCE"):
num == 10 ? input.symbol(defval="BINANCE"): num == 11 ? input.symbol(defval="BINANCE"):
num == 12 ? input.symbol(defval="BINANCE"): na
// | CALCULATION |
//Order
[colMtx, order] = switch sortTable
"High-Low C/H" => [1, order.descending]
"Low-High C/H" => [1, order.ascending ]
"High-Low C/O" => [2, order.descending]
"Low-High C/O" => [2, order.ascending ]
"High-Low C/L" => [3, order.descending]
"Low-High C/L" => [3, order.ascending ]
=> [0, order.ascending]
// Matrix
sectors = matrix.new<float>(13, 4, na)
// Fill Matrix Function
fun_matrix(mtxName, row, adj) =>
// Symbol Name
string sym= symbol(row, "symbols")
s = ticker.modify(sym, syminfo.session)
// Symbol code
matrix.set(mtxName, row + adj, 0, row)
// C/H
ch = request.security(s, timeframe.period, (close[0]/high[0]))
matrix.set(mtxName, row + adj, 1, ch)
// C/O
co = request.security(s, timeframe.period, (close[0]/open[0]))
matrix.set(mtxName, row + adj, 2, co)
// C/L
cl = request.security(s, timeframe.period, (close[0]/low[0]))
matrix.set(mtxName, row + adj, 3, cl)
//++++++++++ Sector Matrix
fun_matrix(sectors, 0, 0)
fun_matrix(sectors, 1, 0)
fun_matrix(sectors, 2, 0)
fun_matrix(sectors, 3, 0)
fun_matrix(sectors, 4, 0)
fun_matrix(sectors, 5, 0)
fun_matrix(sectors, 6, 0)
fun_matrix(sectors, 7, 0)
fun_matrix(sectors, 8, 0)
fun_matrix(sectors, 9, 0)
fun_matrix(sectors, 10, 0)
fun_matrix(sectors, 11, 0)
fun_matrix(sectors, 12, 0)
matrix.sort(sectors, colMtx, order)
// | Table |
// Get Table Position
table_pos(p) =>
switch p
"Top Right" => position.top_right
"Middle Right" => position.middle_right
"Bottom Right" => position.bottom_right
"Top Center" => position.top_center
"Middle Center" => position.middle_center
"Bottom Center" => position.bottom_center
"Top Left" => position.top_left
"Middle Left" => position.middle_left
=> position.bottom_left
// Get Table Size
table_size(s) =>
switch s
"Auto" => size.auto
"Huge" => size.huge
"Large" => size.large
"Normal" => size.normal
"Small" => size.small
=> size.tiny
tz = table_size(in_table_size)
// Get Title Column
fun_titlCol(tbl, col, txtCol) =>
table.cell(tbl, col, 0, text_halign =text.align_left,
text = txtCol,
text_color = title_textCol,
text_size = tz,
bgcolor = background_col)
// Get Cell Values
fun_cell(tbl, row, mtxName, mtxRow) =>
changePerc = matrix.get(mtxName, mtxRow, 2)
calll = (changePerc-1)
bgColor = (calll < 0 ? color.rgb(255,106,106,0):color.rgb(106,255,106,0))
table.cell(tbl, 0, row, text_halign=text.align_right, text_valign=text.align_center,
text = sym_short(symbol(matrix.get(mtxName, mtxRow, 0), "symbols")),
text_color = title_textCol, text_size = tz, bgcolor= background_col)
table.cell(tbl, 1, row, text_halign=text.align_right, text_valign=text.align_center,
text = str.tostring(matrix.get(mtxName,mtxRow,1),"#.####"),
text_color = cell_textCol, text_size = tz, bgcolor = bgColor)
table.cell(tbl, 2, row, text_halign=text.align_right, text_valign=text.align_center,
text = str.tostring(matrix.get(mtxName,mtxRow,2),"#.####"),
text_color = cell_textCol, text_size = tz, bgcolor = bgColor)
table.cell(tbl, 3, row, text_halign=text.align_right, text_valign=text.align_center,
text = str.tostring(matrix.get(mtxName,mtxRow,3),"#.####"),
text_color = cell_textCol, text_size = tz, bgcolor = bgColor)
// Create Table
var tbl = table.new(table_pos(in_table_pos), 4, 14, frame_width = 5,
border_width = 1, border_color = color.new(title_textCol, 100))
// Fill up Cells.
if barstate.islast
table.clear(tbl, 0, 0, 3, 13)
// columns
fun_titlCol(tbl, 0, "Symbol")
fun_titlCol(tbl, 1, "C/H=1 $:LONG \nC/H<1 $:UNSTABLE \n.")
fun_titlCol(tbl, 2, "C/O>1 $:LONG \nC/O=1 $:STABLE \nC/O<1 $:SHORT")
fun_titlCol(tbl, 3, ". \nC/L>1 $:UNSTABLE \nC/L=1 $:SHORT")
for i = 1 to 13
fun_cell(tbl, i, sectors, i - 1) |
Braid Filter+ | https://www.tradingview.com/script/zz615hRE-Braid-Filter/ | bjr117 | https://www.tradingview.com/u/bjr117/ | 165 | 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 = "Braid Filter+", shorttitle = "BF+", overlay = false, timeframe = "", timeframe_gaps = false)
//==============================================================================
// Function: Calculate a given type of moving average
//==============================================================================
get_ma_out(type, src, len, alma_offset, alma_sigma, kama_fastLength, kama_slowLength, vama_vol_len, vama_do_smth, vama_smth, mf_beta, mf_feedback, mf_z, eit_alpha, ssma_pow, ssma_smooth, rsrma_pw, svama_method, svama_vol_or_volatility, wrma_smooth) =>
float baseline = 0.0
if type == "SMA | Simple MA"
baseline := ta.sma(src, len)
else if type == "EMA | Exponential MA"
baseline := ta.ema(src, len)
else if type == "DEMA | Double Exponential MA"
e = ta.ema(src, len)
baseline := 2 * e - ta.ema(e, len)
else if type == "TEMA | Triple Exponential MA"
e = ta.ema(src, len)
baseline := 3 * (e - ta.ema(e, len)) + ta.ema(ta.ema(e, len), len)
else if type == "TMA | Triangular MA" // by everget
baseline := ta.sma(ta.sma(src, math.ceil(len / 2)), math.floor(len / 2) + 1)
else if type == "WMA | Weighted MA"
baseline := ta.wma(src, len)
else if type == "VWMA | Volume-Weighted MA"
baseline := ta.vwma(src, len)
else if type == "SMMA | Smoothed MA"
w = ta.wma(src, len)
baseline := na(w[1]) ? ta.sma(src, len) : (w[1] * (len - 1) + src) / len
else if type == "RMA | Rolling MA"
baseline := ta.rma(src, len)
else if type == "HMA | Hull MA"
baseline := ta.wma(2 * ta.wma(src, len / 2) - ta.wma(src, len), math.round(math.sqrt(len)))
else if type == "LSMA | Least Squares MA"
baseline := ta.linreg(src, len, 0)
else if type == "Kijun" //Kijun-sen
kijun = math.avg(ta.lowest(len), ta.highest(len))
baseline := kijun
else if type == "MD | McGinley Dynamic"
mg = 0.0
mg := na(mg[1]) ? ta.ema(src, len) : mg[1] + (src - mg[1]) / (len * math.pow(src / mg[1], 4))
baseline := mg
else if type == "JMA | Jurik MA" // by everget
DEMAe1 = ta.ema(src, len)
DEMAe2 = ta.ema(DEMAe1, len)
baseline := 2 * DEMAe1 - DEMAe2
else if type == "ALMA | Arnaud Legoux MA"
baseline := ta.alma(src, len, alma_offset, alma_sigma)
else if type == "VAR | Vector Autoregression MA"
valpha = 2 / (len+1)
vud1 = (src > src[1]) ? (src - src[1]) : 0
vdd1 = (src < src[1]) ? (src[1] - src) : 0
vUD = math.sum(vud1, 9)
vDD = math.sum(vdd1, 9)
vCMO = nz( (vUD - vDD) / (vUD + vDD) )
baseline := nz(valpha * math.abs(vCMO) * src) + (1 - valpha * math.abs(vCMO)) * nz(baseline[1])
else if type == "ZLEMA | Zero-Lag Exponential MA" // by HPotter
xLag = (len) / 2
xEMAData = (src + (src - src[xLag]))
baseline := ta.ema(xEMAData, len)
else if type == "AHMA | Ahrens Moving Average" // by everget
baseline := nz(baseline[1]) + (src - (nz(baseline[1]) + nz(baseline[len])) / 2) / len
else if type == "EVWMA | Elastic Volume Weighted MA"
volumeSum = math.sum(volume, len)
baseline := ( (volumeSum - volume) * nz(baseline[1]) + volume * src ) / volumeSum
else if type == "SWMA | Sine Weighted MA" // by everget
sum = 0.0
weightSum = 0.0
for i = 0 to len - 1
weight = math.sin(i * math.pi / (len + 1))
sum := sum + nz(src[i]) * weight
weightSum := weightSum + weight
baseline := sum / weightSum
else if type == "LMA | Leo MA"
baseline := 2 * ta.wma(src, len) - ta.sma(src, len)
else if type == "VIDYA | Variable Index Dynamic Average" // by KivancOzbilgic
mom = ta.change(src)
upSum = math.sum(math.max(mom, 0), len)
downSum = math.sum(-math.min(mom, 0), len)
out = (upSum - downSum) / (upSum + downSum)
cmo = math.abs(out)
alpha = 2 / (len + 1)
baseline := src * alpha * cmo + nz(baseline[1]) * (1 - alpha * cmo)
else if type == "FRAMA | Fractal Adaptive MA"
length2 = math.floor(len / 2)
hh2 = ta.highest(length2)
ll2 = ta.lowest(length2)
N1 = (hh2 - ll2) / length2
N2 = (hh2[length2] - ll2[length2]) / length2
N3 = (ta.highest(len) - ta.lowest(len)) / len
D = (math.log(N1 + N2) - math.log(N3)) / math.log(2)
factor = math.exp(-4.6 * (D - 1))
baseline := factor * src + (1 - factor) * nz(baseline[1])
else if type == "VMA | Variable MA" // by LazyBear
k = 1.0/len
pdm = math.max((src - src[1]), 0)
mdm = math.max((src[1] - src), 0)
pdmS = float(0.0)
mdmS = float(0.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 = float(0.0)
mdiS = float(0.0)
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 = float(0.0)
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
baseline := (1 - k*vI)*nz(baseline[1]) + k*vI*src
else if type == "GMMA | Geometric Mean MA"
lmean = math.log(src)
smean = math.sum(lmean, len)
baseline := math.exp(smean / len)
else if type == "CMA | Corrective MA" // by everget
sma = ta.sma(src, len)
baseline := sma
v1 = ta.variance(src, len)
v2 = math.pow(nz(baseline[1], baseline) - baseline, 2)
v3 = v1 == 0 or v2 == 0 ? 1 : v2 / (v1 + v2)
var tolerance = math.pow(10, -5)
float err = 1
// Gain Factor
float kPrev = 1
float k = 1
for i = 0 to 5000 by 1
if err > tolerance
k := v3 * kPrev * (2 - kPrev)
err := kPrev - k
kPrev := k
kPrev
baseline := nz(baseline[1], src) + k * (sma - nz(baseline[1], src))
else if type == "MM | Moving Median" // by everget
baseline := ta.percentile_nearest_rank(src, len, 50)
else if type == "QMA | Quick MA" // by everget
peak = len / 3
num = 0.0
denom = 0.0
for i = 1 to len + 1
mult = 0.0
if i <= peak
mult := i / peak
else
mult := (len + 1 - i) / (len + 1 - peak)
num := num + src[i - 1] * mult
denom := denom + mult
baseline := (denom != 0.0) ? (num / denom) : src
else if type == "KAMA | Kaufman Adaptive MA" // by everget
mom = math.abs(ta.change(src, len))
volatility = math.sum(math.abs(ta.change(src)), len)
// Efficiency Ratio
er = volatility != 0 ? mom / volatility : 0
fastAlpha = 2 / (kama_fastLength + 1)
slowAlpha = 2 / (kama_slowLength + 1)
alpha = math.pow(er * (fastAlpha - slowAlpha) + slowAlpha, 2)
baseline := alpha * src + (1 - alpha) * nz(baseline[1], src)
else if type == "VAMA | Volatility Adjusted MA" // by Joris Duyck (JD)
mid = ta.ema(src, len)
dev = src - mid
vol_up = ta.highest(dev, vama_vol_len)
vol_down = ta.lowest(dev, vama_vol_len)
vama = mid + math.avg(vol_up, vol_down)
baseline := vama_do_smth ? ta.wma(vama, vama_smth) : vama
else if type == "Modular Filter" // by alexgrover
//----
b = 0.0, c = 0.0, os = 0.0, ts = 0.0
//----
alpha = 2/(len+1)
a = mf_feedback ? mf_z*src + (1-mf_z)*nz(baseline[1],src) : src
//----
b := a > alpha*a+(1-alpha)*nz(b[1],a) ? a : alpha*a+(1-alpha)*nz(b[1],a)
c := a < alpha*a+(1-alpha)*nz(c[1],a) ? a : alpha*a+(1-alpha)*nz(c[1],a)
os := a == b ? 1 : a == c ? 0 : os[1]
//----
upper = mf_beta*b+(1-mf_beta)*c
lower = mf_beta*c+(1-mf_beta)*b
baseline := os*upper+(1-os)*lower
else if type == "EIT | Ehlers Instantaneous Trendline" // by Franklin Moormann (cheatcountry)
baseline := bar_index < 7 ? (src + (2 * nz(src[1])) + nz(src[2])) / 4 : ((eit_alpha - (math.pow(eit_alpha, 2) / 4)) * src) + (0.5 * math.pow(eit_alpha, 2) * nz(src[1])) -
((eit_alpha - (0.75 * math.pow(eit_alpha, 2))) * nz(src[2])) + (2 * (1 - eit_alpha) * nz(baseline[1])) - (math.pow(1 - eit_alpha, 2) * nz(baseline[2]))
else if type == "ESD | Ehlers Simple Decycler" // by everget
// High-pass Filter
alphaArg = 2 * math.pi / (len * math.sqrt(2))
alpha = 0.0
alpha := math.cos(alphaArg) != 0
? (math.cos(alphaArg) + math.sin(alphaArg) - 1) / math.cos(alphaArg)
: nz(alpha[1])
hp = 0.0
hp := math.pow(1 - (alpha / 2), 2) * (src - 2 * nz(src[1]) + nz(src[2])) + 2 * (1 - alpha) * nz(hp[1]) - math.pow(1 - alpha, 2) * nz(hp[2])
baseline := src - hp
else if type == "SSMA | Shapeshifting MA" // by alexgrover
//----
ssma_sum = 0.0
ssma_sumw = 0.0
alpha = ssma_smooth ? 2 : 1
power = ssma_smooth ? ssma_pow - ssma_pow % 2 : ssma_pow
//----
for i = 0 to len-1
x = i/(len-1)
n = ssma_smooth ? -1 + x*2 : x
w = 1 - 2*math.pow(n,alpha)/(math.pow(n,power) + 1)
ssma_sumw := ssma_sumw + w
ssma_sum := ssma_sum + src[i] * w
baseline := ssma_sum/ssma_sumw
//----
else if type == "RSRMA | Right Sided Ricker MA" // by alexgrover
//----
rsrma_sum = 0.0
rsrma_sumw = 0.0
rsrma_width = rsrma_pw/100*len
for i = 0 to len-1
w = (1 - math.pow(i/rsrma_width,2))*math.exp(-(i*i/(2*math.pow(rsrma_width,2))))
rsrma_sumw := rsrma_sumw + w
rsrma_sum := rsrma_sum + src[i] * w
baseline := rsrma_sum/rsrma_sumw
//----
else if type == "DSWF | Damped Sine Wave Weighted Filter" // by alexgrover
//----
dswf_sum = 0.0
dswf_sumw = 0.0
for i = 1 to len
w = math.sin(2.0*math.pi*i/len)/i
dswf_sumw := dswf_sumw + w
dswf_sum := dswf_sum + w*src[i-1]
//----
baseline := dswf_sum/dswf_sumw
else if type == "BMF | Blackman Filter" // by alexgrover
//----
bmf_sum = 0.0
bmf_sumw = 0.0
for i = 0 to len-1
k = i/len
w = 0.42 - 0.5 * math.cos(2 * math.pi * k) + 0.08 * math.cos(4 * math.pi * k)
bmf_sumw := bmf_sumw + w
bmf_sum := bmf_sum + w*src[i]
//----
baseline := bmf_sum/bmf_sumw
else if type == "HCF | Hybrid Convolution Filter" // by alexgrover
//----
sum = 0.
for i = 1 to len
sgn = .5*(1 - math.cos((i/len)*math.pi))
sum := sum + (sgn*(nz(baseline[1],src)) + (1 - sgn)*src[i-1]) * ( (.5*(1 - math.cos((i/len)*math.pi))) - (.5*(1 - math.cos(((i-1)/len)*math.pi))) )
baseline := sum
//----
else if type == "FIR | Finite Response Filter" // by alexgrover
//----
var b = array.new_float(0)
if barstate.isfirst
for i = 0 to len-1
w = len-i
array.push(b,w)
den = array.sum(b)
//----
sum = 0.0
for i = 0 to len-1
sum := sum + src[i]*array.get(b,i)
baseline := sum/den
else if type == "FLSMA | Fisher Least Squares MA" // by alexgrover
//----
b = 0.0
//----
e = ta.sma(math.abs(src - nz(b[1])),len)
z = ta.sma(src - nz(b[1],src),len)/e
r = (math.exp(2*z) - 1)/(math.exp(2*z) + 1)
a = (bar_index - ta.sma(bar_index,len))/ta.stdev(bar_index,len) * r
b := ta.sma(src,len) + a*ta.stdev(src,len)
baseline := b
else if type == "SVAMA | Non-Parametric Volume Adjusted MA" // by alexgrover and bjr117
//----
h = 0.0
l = 0.0
c = 0.0
//----
a = svama_vol_or_volatility == "Volume" ? volume : ta.tr
h := a > nz(h[1], a) ? a : nz(h[1], a)
l := a < nz(l[1], a) ? a : nz(l[1], a)
//----
b = svama_method == "Max" ? a / h : l / a
c := b * close + (1 - b) * nz(c[1], close)
baseline := c
else if type == "RPMA | Repulsion MA" // by alexgrover
baseline := ta.sma(close, len*3) + ta.sma(close, len*2) - ta.sma(close, len)
else if type == "WRMA | Well Rounded MA" // by alexgrover
//----
alpha = 2/(len+1)
p1 = wrma_smooth ? len/4 : 1
p2 = wrma_smooth ? len/4 : len/2
//----
a = float(0.0)
b = float(0.0)
y = ta.ema(a + b,p1)
A = src - y
B = src - ta.ema(y,p2)
a := nz(a[1]) + alpha*nz(A[1])
b := nz(b[1]) + alpha*nz(B[1])
baseline := y
else if type == "HLT | HiLo Trend"
// Getting the highest highs / lowest lows in the user-inputted slowLength period and fastLength period
hlt_high = ta.highest(src, len)
hlt_low = ta.lowest(src, len)
// Calculate the HLT Line
// If the source (close, hl2, ...) value is greater than the previous HLT line, let the next HLT line value be the source value.
baseline := (src > baseline[1]) ? hlt_low : hlt_high
else if type == "T3 | Tillson T3" // by HPotter
////////////////////////////////////////////////////////////
// Copyright by HPotter v1.0 21/05/2014
// This indicator plots the moving average described in the January, 1998 issue
// of S&C, p.57, "Smoothing Techniques for More Accurate Signals", by Tim Tillson.
// This indicator plots T3 moving average presented in Figure 4 in the article.
// T3 indicator is a moving average which is calculated according to formula:
// T3(n) = GD(GD(GD(n))),
// where GD - generalized DEMA (Double EMA) and calculating according to this:
// GD(n,v) = EMA(n) * (1+v)-EMA(EMA(n)) * v,
// where "v" is volume factor, which determines how hot the moving average’s response
// to linear trends will be. The author advises to use v=0.7.
// When v = 0, GD = EMA, and when v = 1, GD = DEMA. In between, GD is a less aggressive
// version of DEMA. By using a value for v less than1, trader cure the multiple DEMA
// overshoot problem but at the cost of accepting some additional phase delay.
// In filter theory terminology, T3 is a six-pole nonlinear Kalman filter. Kalman
// filters are ones that use the error — in this case, (time series - EMA(n)) —
// to correct themselves. In the realm of technical analysis, these are called adaptive
// moving averages; they track the time series more aggres-sively when it is making large
// moves. Tim Tillson is a software project manager at Hewlett-Packard, with degrees in
// mathematics and computer science. He has privately traded options and equities for 15 years.
////////////////////////////////////////////////////////////
xe1 = ta.ema(src, len)
xe2 = ta.ema(xe1, len)
xe3 = ta.ema(xe2, len)
xe4 = ta.ema(xe3, len)
xe5 = ta.ema(xe4, len)
xe6 = ta.ema(xe5, len)
b = 0.7
c1 = -b*b*b
c2 = 3*b*b+3*b*b*b
c3 = -6*b*b-3*b-3*b*b*b
c4 = 1+3*b+b*b*b+3*b*b
baseline := c1 * xe6 + c2 * xe5 + c3 * xe4 + c4 * xe3
baseline
//==============================================================================
//==============================================================================
// Inputs
//==============================================================================
// Main settings
bf_ma_type = input.string("EMA | Exponential MA", "MA Type", options=[ "EMA | Exponential MA", "SMA | Simple MA",
"WMA | Weighted MA", "DEMA | Double Exponential MA",
"TEMA | Triple Exponential MA", "TMA | Triangular MA",
"VWMA | Volume-Weighted MA", "SMMA | Smoothed MA",
"HMA | Hull MA", "LSMA | Least Squares MA",
"Kijun", "MD | McGinley Dynamic",
"RMA | Rolling MA", "JMA | Jurik MA",
"ALMA | Arnaud Legoux MA", "VAR | Vector Autoregression MA",
"ZLEMA | Zero-Lag Exponential MA", "T3 | Tillson T3",
"AHMA | Ahrens Moving Average", "EVWMA | Elastic Volume Weighted MA",
"SWMA | Sine Weighted MA", "LMA | Leo MA",
"VIDYA | Variable Index Dynamic Average", "FRAMA | Fractal Adaptive MA",
"VMA | Variable MA", "GMMA | Geometric Mean MA",
"CMA | Corrective MA", "MM | Moving Median",
"QMA | Quick MA", "KAMA | Kaufman Adaptive MA",
"VAMA | Volatility Adjusted MA", "Modular Filter",
"EIT | Ehlers Instantaneous Trendline", "ESD | Ehlers Simple Decycler",
"SSMA | Shapeshifting MA", "RSRMA | Right Sided Ricker MA",
"DSWF | Damped Sine Wave Weighted Filter", "BMF | Blackman Filter",
"HCF | Hybrid Convolution Filter", "FIR | Finite Response Filter",
"FLSMA | Fisher Least Squares MA", "SVAMA | Non-Parametric Volume Adjusted MA",
"RPMA | Repulsion MA", "WRMA | Well Rounded MA",
"HLT | HiLo Trend"
], group = "Main Braid Filter Settings")
bf_ma_src = input.source(title = "MA Source", defval = close, group = "Main Braid Filter Settings")
bf_len_1 = input.int(title = "Fast Source Price MA Length", defval = 3, minval = 1, group = "Main Braid Filter Settings")
bf_len_2 = input.int(title = "Open Price MA Length", defval = 7, minval = 1, group = "Main Braid Filter Settings")
bf_len_3 = input.int(title = "Slow Source Price MA Length", defval = 14, minval = 1, group = "Main Braid Filter Settings")
bf_filter_strength = input.float(title = "Filter Strength", defval = 40.0, minval = 1.0, step = 1.0, group = "Main Braid Filter Settings")
bf_atr_len = input.int(title = "ATR Length", defval = 14, minval = 1, group = "Main Braid Filter Settings")
// Display settings
bf_color_bars = input.bool(title = "Color Bars?", defval = false, group = "Braid Filter Display Settings")
bf_show_sigs = input.bool(title = "Show Signals?", defval = false, group = "Braid Filter Display Settings")
// Specific MA Settings
bf_ma1_alma_offset = input.float(title = "Offset", defval = 0.85, step = 0.05, group = "Braid Filter ALMA Settings")
bf_ma1_alma_sigma = input.int(title = "Sigma", defval = 6, group = "Braid Filter ALMA Settings")
bf_ma1_kama_fastLength = input(title = "Fast EMA Length", defval=2, group = "Braid Filter KAMA Settings")
bf_ma1_kama_slowLength = input(title = "Slow EMA Length", defval=30, group = "Braid Filter KAMA Settings")
bf_ma1_vama_vol_len = input.int(title = "Volatality Length", defval = 51, group = "Braid Filter VAMA Settings")
bf_ma1_vama_do_smth = input.bool(title = "Do Smoothing?", defval = false, group = "Braid Filter VAMA Settings")
bf_ma1_vama_smth = input.int(title = "Smoothing length", defval = 5, minval = 1, group = "Braid Filter VAMA Settings")
bf_ma1_mf_beta = input.float(title = "Beta", defval = 0.8, step = 0.1, minval = 0, maxval=1, group = "Braid Filter Modular Filter Settings")
bf_ma1_mf_feedback = input.bool(title = "Feedback?", defval = false, group = "Braid Filter Modular Filter Settings")
bf_ma1_mf_z = input.float(title = "Feedback Weighting", defval = 0.5, step = 0.1, minval = 0, maxval = 1, group = "Braid Filter Modular Filter Settings")
bf_ma1_eit_alpha = input.float(title = "Alpha", defval = 0.07, step = 0.01, minval = 0.0, group = "Braid Filter Ehlers Instantaneous Trendline Settings")
bf_ssma1_pow = input.float(title = "Power", defval = 4.0, step = 0.5, minval = 0.0, group = "Braid Filter SSMA Settings")
bf_ssma1_smooth = input.bool(title = "Smooth", defval = false, group = "Braid Filter SSMA Settings")
bf_rsrma1_pw = input.float(title = "Percent Width", defval = 60.0, step = 10.0, minval = 0.0, maxval = 100.0, group = "Braid Filter RSRMA Settings")
bf_svama1_method = input.string(title = "Max", options=["Max", "Min"], defval = "Max", group = "Braid Filter SVAMA Settings")
bf_svama1_vol_or_volatility = input.string(title = "Use Volume or Volatility?", options = ["Volume", "Volatility"], defval = "Volatility", group = "Braid Filter SVAMA Settings")
bf_wrma1_smooth = input.bool(title = "Extra Smoothing?", defval = false, group = "Braid Filter WRMA Settings")
//==============================================================================
//==============================================================================
// Calculating the Braid Filter
//==============================================================================
// Calculating an average of the source price with a low lookback period
bf_fast_src_ma = get_ma_out(bf_ma_type, bf_ma_src, bf_len_1, bf_ma1_alma_offset, bf_ma1_alma_sigma, bf_ma1_kama_fastLength, bf_ma1_kama_slowLength, bf_ma1_vama_vol_len, bf_ma1_vama_do_smth, bf_ma1_vama_smth, bf_ma1_mf_beta, bf_ma1_mf_feedback, bf_ma1_mf_z, bf_ma1_eit_alpha, bf_ssma1_pow, bf_ssma1_smooth, bf_rsrma1_pw, bf_svama1_method, bf_svama1_vol_or_volatility, bf_wrma1_smooth)
// Calculating an average of the open price with a low lookback period
bf_open_ma = get_ma_out(bf_ma_type, open, bf_len_2, bf_ma1_alma_offset, bf_ma1_alma_sigma, bf_ma1_kama_fastLength, bf_ma1_kama_slowLength, bf_ma1_vama_vol_len, bf_ma1_vama_do_smth, bf_ma1_vama_smth, bf_ma1_mf_beta, bf_ma1_mf_feedback, bf_ma1_mf_z, bf_ma1_eit_alpha, bf_ssma1_pow, bf_ssma1_smooth, bf_rsrma1_pw, bf_svama1_method, bf_svama1_vol_or_volatility, bf_wrma1_smooth)
// Calculating an average of the source price with a high lookback period
bf_slow_src_ma = get_ma_out(bf_ma_type, bf_ma_src, bf_len_3, bf_ma1_alma_offset, bf_ma1_alma_sigma, bf_ma1_kama_fastLength, bf_ma1_kama_slowLength, bf_ma1_vama_vol_len, bf_ma1_vama_do_smth, bf_ma1_vama_smth, bf_ma1_mf_beta, bf_ma1_mf_feedback, bf_ma1_mf_z, bf_ma1_eit_alpha, bf_ssma1_pow, bf_ssma1_smooth, bf_rsrma1_pw, bf_svama1_method, bf_svama1_vol_or_volatility, bf_wrma1_smooth)
// Determining whether the average source price MA is greater than the average open price, and then determining whether the highest one out of those two is greater than the slow average source price.
bf_ma_max = math.max(math.max(bf_fast_src_ma, bf_open_ma), bf_slow_src_ma)
// Determining whether the average source price MA is greater than the average open price, and then determining whether the highest one out of those two is greater than the slow average source price.
bf_ma_min = math.min(math.min(bf_fast_src_ma, bf_open_ma), bf_slow_src_ma)
// Calculating the braid filter's histogram by taking the difference between the highest average price out of the three calculated above, and subtracting it by the lowest average price out of the three calculated above.
bf_histo = bf_ma_max - bf_ma_min
// Calculating the braid filter's "deadzone" line by multiplying the average true range by the filter strength (a constant inputted by the user; higher values increase the strictness of the filter), and then dividing that resulting value by 100 to make the filter fit the histogram.
bf_filter = ta.atr(bf_atr_len) * bf_filter_strength / 100.0
//==============================================================================
//==============================================================================
// Calculating the Braid Filter's signals
//==============================================================================
is_histo_above_filter = bf_histo > bf_filter
is_histo_bar_bullish = bf_fast_src_ma > bf_open_ma
is_histo_bar_bearish = bf_fast_src_ma < bf_open_ma
// True if the histogram bar switches to green and is above the filter, false otherwise
bf_L_trig = is_histo_above_filter and (ta.crossover(bf_fast_src_ma, bf_open_ma) or (ta.crossover(bf_histo, bf_filter) and is_histo_bar_bullish))
// True if the histogram bar switches to red and is above the filter, false otherwise
bf_S_trig = is_histo_above_filter and (ta.crossunder(bf_fast_src_ma, bf_open_ma) or (ta.crossover(bf_histo, bf_filter) and is_histo_bar_bearish))
// True if the histogram bar switches to and remains green and is above the filter, false otherwise
bf_L_conf = is_histo_above_filter and is_histo_bar_bullish
// True if the histogram bar switches to and remains green and is above the filter, false otherwise
bf_S_conf = is_histo_above_filter and is_histo_bar_bearish
//==============================================================================
//==============================================================================
// Plotting the Braid Filter
//==============================================================================
bf_color = bf_L_conf ? color.green : bf_S_conf ? color.red : color.gray
plot(bf_histo, title = "Braid Filter Histogram", color = bf_color, style = plot.style_columns)
plot(bf_filter, title = "Braid Filter Line", color = color.black)
barcolor(bf_color_bars ? bf_color : na, title = "Braid Filter Bar Color")
// Plotting buy and sell signals
plotshape(bf_L_trig and bf_show_sigs ? bf_histo : na, title="Braid Filter Long Signal", location=location.top, style=shape.triangleup, size=size.tiny, color=color.new(color.green, 30), textcolor=color.new(color.black, 0))
plotshape(bf_S_trig and bf_show_sigs ? bf_histo : na, title="Braid Filter Short Signal", location=location.top, style=shape.triangledown, size=size.tiny, color=color.new(color.red, 30), textcolor=color.new(color.black, 0))
//==============================================================================
//==============================================================================
// Braid Filter Alerts
//==============================================================================
alertcondition(bf_L_trig, title = "Braid Filter Long Signal", message = "{{ticker}}: Braid Filter signaled to go long at {{time}}.")
alertcondition(bf_S_trig, title = "Braid Filter Short Signal", message = "{{ticker}}: Braid Filter signaled to go short at {{time}}.")
//==============================================================================
|
Detect BOS in Five Candles with MTF - Alert [MsF] | https://www.tradingview.com/script/lk6YQV9U/ | Trader_Morry | https://www.tradingview.com/u/Trader_Morry/ | 331 | 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/
// © Trader_Morry
//@version=5
indicator("Detect BOS in Five Candles with MTF - Alert [MsF]", shorttitle = "Detect BOS /w MTF", overlay = true)
var GRP1 = "--- Time Frame Settings ---"
TF1 = input.timeframe("60", group = GRP1)
TF2 = input.timeframe("240", group = GRP1)
var GRP2 = "--- MTF Candles Settings ---"
show_HTF1_Candles = input.bool(true, title = "show_MTF1_Candles", group = GRP2)
show_HTF2_Candles = input.bool(true, title = "show_MTF2_Candles", group = GRP2)
show_Labels = input.bool(true, title = "show_OHLC_Labels", group = GRP2)
show_RemainTime = input.bool(true, title = "show_Remain_Time", group = GRP2)
chart_color_up = input.color(color.lime, group = GRP2)
chart_color_even = input.color(color.white, group = GRP2)
chart_color_down = input.color(color.red, group = GRP2)
offset_HTF_Candles = input.int(0, title = "Candles OFFSET", group = GRP2)
var GRP21 = "--- High/Low Lines Settings ---"
show_HLLines_1 = input.bool(false, title = "", inline='1', group = GRP21)
lineColor_1 = input.color(defval=color.rgb( 255, 235, 59, 50), title='MTF1', inline='1', group = GRP21)
lineStyle_1 = input.string(title='Style', defval=line.style_dotted, options=[line.style_dotted, line.style_dashed, line.style_solid], inline = "1", group = GRP21)
lineWidth_1 = input.int(title='Width', defval=1, inline = "1", group = GRP21)
show_HLLines_2 = input.bool(false, title = "", inline='2', group = GRP21)
lineColor_2 = input.color(defval=color.rgb( 255, 255, 255, 70), title='MTF2', inline='2', group = GRP21)
lineStyle_2 = input.string(title='Style', defval=line.style_dashed, options=[line.style_dotted, line.style_dashed, line.style_solid], inline = "2", group = GRP21)
lineWidth_2 = input.int(title='Width', defval=1, inline = "2", group = GRP21)
var GRP3 = "--- MTF BOS Settings ---"
show_BOS_Lines = input.bool(true, title = "show_BOS_Lines", group = GRP3)
show_BOS_Labels = input.bool(true, title = "show_BOS_Labels", group = GRP3)
line_color_BOS = input.color(color.blue, group = GRP3, inline = "BOS_line")
line_width_BOS = input.int(defval = 1, minval = 1, title = "width", group = GRP3, inline = "BOS_line")
show_HTF1_BOSlines = show_BOS_Lines //input.bool(true)
show_HTF2_BOSlines = show_BOS_Lines //input.bool(true)
////////////////
// functions
// [
convert_mSecToTime(aMsec) =>
_sTime = ""
iMsec = aMsec
if syminfo.type != "crypto"
iMsec := aMsec - (19 * 1000 * 60 * 60) + (1 * 1000 * 60 * 60 * 24) // 帳尻合わせ:19時間引いて、1日足す
iSec = second(iMsec)
iMin = minute(iMsec)
iHour = hour(iMsec)
iDay = math.floor(iMsec / 1000 / 60 / 60 / 24)
if iDay > 0
_sTime := _sTime + str.tostring(iDay) + "D " + str.format_time(iMsec, "HH:mm:ss", syminfo.timezone)
else if iHour > 0
_sTime := _sTime + str.format_time(iMsec, "HH:mm:ss", syminfo.timezone)
else
_sTime := _sTime + str.format_time(iMsec, "mm:ss", syminfo.timezone)
_sTime
// ]
////////////////
[O_,H_,L_,C_, O_1,H_1,L_1,C_1, O_2,H_2,L_2,C_2, O_3,H_3,L_3,C_3, O_4,H_4,L_4,C_4] = request.security(syminfo.tickerid, TF1, [open[0], high[0], low[0], close[0], open[1], high[1], low[1], close[1], open[2], high[2], low[2], close[2], open[3], high[3], low[3], close[3], open[4], high[4], low[4], close[4]])
[DO_,DH_,DL_,DC_, DO_1,DH_1,DL_1,DC_1, DO_2,DH_2,DL_2,DC_2, DO_3,DH_3,DL_3,DC_3, DO_4,DH_4,DL_4,DC_4] = request.security(syminfo.tickerid, TF2, [open[0], high[0], low[0], close[0], open[1], high[1], low[1], close[1], open[2], high[2], low[2], close[2], open[3], high[3], low[3], close[3], open[4], high[4], low[4], close[4]])
var line line_H_L = na
var line line_H_L_1 = na
var line line_H_L_2 = na
var line line_H_L_3 = na
var line line_H_L_4 = na
var line line_O_C = na
var line line_O_C_1 = na
var line line_O_C_2 = na
var line line_O_C_3 = na
var line line_O_C_4 = na
var label label_O = na
var label label_H = na
var label label_L = na
var label label_C = na
var label label_LL = na
var label label_RT = na
var label label_BS_H = na
var label label_BS_L = na
var line line_HTF1_BOS_H1 = na // ひとつ前の足で引くライン
var line line_HTF1_BOS_H0 = na // 今の足で引くライン
var line line_HTF1_BOS_L1 = na // ひとつ前の足で引くライン
var line line_HTF1_BOS_L0 = na // 今の足で引くライン
var bool alert_HTF1_BOS_1 = false // アラート判定ひとつ前の足確定時
var bool alert_HTF1_BOS_0 = false // アラート判定今の足でBreak時
var line line_HTF1_H = na
var line line_HTF1_L = na
var line line_D_H_L = na
var line line_D_H_L_1 = na
var line line_D_H_L_2 = na
var line line_D_H_L_3 = na
var line line_D_H_L_4 = na
var line line_D_O_C = na
var line line_D_O_C_1 = na
var line line_D_O_C_2 = na
var line line_D_O_C_3 = na
var line line_D_O_C_4 = na
var label label_D_O = na
var label label_D_H = na
var label label_D_L = na
var label label_D_C = na
var label label_D_LL = na
var label label_D_RT = na
var label label_D_BS_H = na
var label label_D_BS_L = na
var line line_HTF2_BOS_H1 = na // ひとつ前の足で引くライン
var line line_HTF2_BOS_H0 = na // 今の足で引くライン
var line line_HTF2_BOS_L1 = na // ひとつ前の足で引くライン
var line line_HTF2_BOS_L0 = na // 今の足で引くライン
var bool alert_HTF2_BOS_1 = false // アラート判定ひとつ前の足確定時
var bool alert_HTF2_BOS_0 = false // アラート判定今の足でBreak時
var line line_HTF2_H = na
var line line_HTF2_L = na
// MTFキャンドルの描画スタート位置=オフセットを加味したバーインデックス
htf_candles_startingPos = bar_index + offset_HTF_Candles
if show_HTF1_Candles
line.delete(line_H_L)
line.delete(line_H_L_1)
line.delete(line_H_L_2)
line.delete(line_H_L_3)
line.delete(line_H_L_4)
line.delete(line_O_C)
line.delete(line_O_C_1)
line.delete(line_O_C_2)
line.delete(line_O_C_3)
line.delete(line_O_C_4)
label.delete(label_O)
label.delete(label_H)
label.delete(label_L)
label.delete(label_C)
label.delete(label_LL)
label.delete(label_RT)
line_H_L := line.new(htf_candles_startingPos + 32, O_, htf_candles_startingPos + 32, C_, color=(O_<C_?chart_color_up:O_>C_?chart_color_down:chart_color_even), width=9)
line_H_L_1 := line.new(htf_candles_startingPos + 29, O_1, htf_candles_startingPos + 29, C_1, color=(O_1<C_1?chart_color_up:O_1>C_1?chart_color_down:chart_color_even), width=9)
line_H_L_2 := line.new(htf_candles_startingPos + 26, O_2, htf_candles_startingPos + 26, C_2, color=(O_2<C_2?chart_color_up:O_2>C_2?chart_color_down:chart_color_even), width=9)
line_H_L_3 := line.new(htf_candles_startingPos + 23, O_3, htf_candles_startingPos + 23, C_3, color=(O_3<C_3?chart_color_up:O_3>C_3?chart_color_down:chart_color_even), width=9)
line_H_L_4 := line.new(htf_candles_startingPos + 20, O_4, htf_candles_startingPos + 20, C_4, color=(O_4<C_4?chart_color_up:O_4>C_4?chart_color_down:chart_color_even), width=9)
line_O_C := line.new(htf_candles_startingPos + 32, H_, htf_candles_startingPos + 32, L_, color=(O_<C_?chart_color_up:O_>C_?chart_color_down:chart_color_even))
line_O_C_1 := line.new(htf_candles_startingPos + 29, H_1, htf_candles_startingPos + 29, L_1, color=(O_1<C_1?chart_color_up:O_1>C_1?chart_color_down:chart_color_even))
line_O_C_2 := line.new(htf_candles_startingPos + 26, H_2, htf_candles_startingPos + 26, L_2, color=(O_2<C_2?chart_color_up:O_2>C_2?chart_color_down:chart_color_even))
line_O_C_3 := line.new(htf_candles_startingPos + 23, H_3, htf_candles_startingPos + 23, L_3, color=(O_3<C_3?chart_color_up:O_3>C_3?chart_color_down:chart_color_even))
line_O_C_4 := line.new(htf_candles_startingPos + 20, H_4, htf_candles_startingPos + 20, L_4, color=(O_4<C_4?chart_color_up:O_4>C_4?chart_color_down:chart_color_even))
if show_HTF1_BOSlines
line.delete(line_HTF1_BOS_H0)
line.delete(line_HTF1_BOS_H1)
line.delete(line_HTF1_BOS_L0)
line.delete(line_HTF1_BOS_L1)
label.delete(label_BS_H)
label.delete(label_BS_L)
alert_HTF1_BOS_0 := false
alert_HTF1_BOS_1 := false
// 5個のローソク番号:[4][3][2][1][0]
// [4][3][2]のローソクから判定する
if L_4>L_3 and L_3<L_2
if H_2<C_1
// [2]と[1]でBOS発生してたらBOS引いてアラート設定
line_HTF1_BOS_H1 := line.new(htf_candles_startingPos + 26, H_2, htf_candles_startingPos + 32, H_2, color=line_color_BOS, width=line_width_BOS)
alert_HTF1_BOS_1 := true
// BOS label
if show_BOS_Labels
label.delete(label_BS_H)
label_BS_H := label.new(htf_candles_startingPos + 48, H_2, text = "BOS: " + str.tostring(H_2), textcolor=line_color_BOS, style=label.style_label_left, color = color.new(chart_color_even, 90))
else
// [2]と[1]でBOS発生してない場合はBOS候補の線(隣のBarまで延長)のみ引く
line_HTF1_BOS_H1 := line.new(htf_candles_startingPos + 26, H_2, htf_candles_startingPos + 35, H_2, color=line_color_BOS, width=line_width_BOS)
if H_2<C_
// [2]のBOS候補の線を[0]で抜いたらアラート設定
alert_HTF1_BOS_0 := true
// BOS label
if show_BOS_Labels
label.delete(label_BS_H)
label_BS_H := label.new(htf_candles_startingPos + 48, H_2, text = "BOS: " + str.tostring(H_2), textcolor=line_color_BOS, style=label.style_label_left, color = color.new(chart_color_even, 90))
if H_4<H_3 and H_3>H_2
if L_2>C_1
// [2]と[1]でBOS発生してたらBOS引いてアラート設定
line_HTF1_BOS_L1 := line.new(htf_candles_startingPos + 26, L_2, htf_candles_startingPos + 32, L_2, color=line_color_BOS, width=line_width_BOS)
alert_HTF1_BOS_1 := true
// BOS label
if show_BOS_Labels
label.delete(label_BS_L)
label_BS_L := label.new(htf_candles_startingPos + 48, L_2, text = "BOS: " + str.tostring(L_2), textcolor=line_color_BOS, style=label.style_label_left, color = color.new(chart_color_even, 90))
else
// [2]と[1]でBOS発生してない場合はBOS候補の線(隣のBarまで延長)のみ引く
line_HTF1_BOS_L1 := line.new(htf_candles_startingPos + 26, L_2, htf_candles_startingPos + 35, L_2, color=line_color_BOS, width=line_width_BOS)
if L_2>C_
// [2]のBOS候補の線を[0]で抜いたらアラート設定
alert_HTF1_BOS_0 := true
// BOS label
if show_BOS_Labels
label.delete(label_BS_L)
label_BS_L := label.new(htf_candles_startingPos + 48, L_2, text = "BOS: " + str.tostring(L_2), textcolor=line_color_BOS, style=label.style_label_left, color = color.new(chart_color_even, 90))
// [3][2][1]のローソクから判定する
if L_3>L_2 and L_2<L_1
line_HTF1_BOS_H0 := line.new(htf_candles_startingPos + 29, H_1, htf_candles_startingPos + 35, H_1, color=line_color_BOS, width=line_width_BOS)
if H_1<C_
// [1]のBOS候補の線を[0]で抜いたらアラート設定
alert_HTF1_BOS_0 := true
// BOS label
if show_BOS_Labels
label.delete(label_BS_H)
label_BS_H := label.new(htf_candles_startingPos + 48, H_1, text = "BOS: " + str.tostring(H_1), textcolor=line_color_BOS, style=label.style_label_left, color = color.new(chart_color_even, 90))
if H_3<H_2 and H_2>H_1
line_HTF1_BOS_L0 := line.new(htf_candles_startingPos + 29, L_1, htf_candles_startingPos + 35, L_1, color=line_color_BOS, width=line_width_BOS)
if L_1>C_
// [1]のBOS候補の線を[0]で抜いたらアラート設定
alert_HTF1_BOS_0 := true
// BOS label
if show_BOS_Labels
label.delete(label_BS_L)
label_BS_L := label.new(htf_candles_startingPos + 48, L_1, text = "BOS: " + str.tostring(L_1), textcolor=line_color_BOS, style=label.style_label_left, color = color.new(chart_color_even, 90))
if show_Labels
label_O := label.new(htf_candles_startingPos + 48, O_, text = "O : " + str.tostring(O_), textcolor=(O_<C_?chart_color_up:O_>C_?chart_color_down:chart_color_even), style=label.style_label_left, color = color.new(chart_color_even, 70))
label_H := label.new(htf_candles_startingPos + 33, H_, text = "H : " + str.tostring(H_), textcolor=(O_<C_?chart_color_up:O_>C_?chart_color_down:chart_color_even), style=label.style_label_left, color = color.new(chart_color_even, 70))
label_L := label.new(htf_candles_startingPos + 48, L_, text = "L : " + str.tostring(L_), textcolor=(O_<C_?chart_color_up:O_>C_?chart_color_down:chart_color_even), style=label.style_label_left, color = color.new(chart_color_even, 70))
label_C := label.new(htf_candles_startingPos + 33, C_, text = "C : " + str.tostring(C_), textcolor=(O_<C_?chart_color_up:O_>C_?chart_color_down:chart_color_even), style=label.style_label_left, color = color.new(chart_color_even, 70))
// [line_H_L,line_H_L_1,line_H_L_2,line_H_L_3,line_H_L_4, line_O_C,line_O_C_1,line_O_C_2,line_O_C_3,line_O_C_4, label_O, label_H, label_L, label_C, label_LL, label_RT]
iHighest = H_
if iHighest < H_1
iHighest := H_1
if iHighest < H_2
iHighest := H_2
if iHighest < H_3
iHighest := H_3
if iHighest < H_4
iHighest := H_4
iLowest = L_
if iLowest > L_1
iLowest := L_1
if iLowest > L_2
iLowest := L_2
if iLowest > L_3
iLowest := L_3
if iLowest > L_4
iLowest := L_4
if show_RemainTime
label_RT := label.new(htf_candles_startingPos + 40, iHighest, text = convert_mSecToTime(time_close(TF1)-timenow), textcolor=(O_<C_?chart_color_up:O_>C_?chart_color_down:chart_color_even), style=label.style_label_right, color = na, size=size.large)
label_LL := label.new(htf_candles_startingPos + 10, (H_ + L_)/2, text = "TF: " + str.tostring(TF1), textcolor=(O_<C_?chart_color_up:O_>C_?chart_color_down:chart_color_even), style=label.style_label_right, color = na, size=size.large)
if show_HLLines_1
line.delete(line_HTF1_H)
line.delete(line_HTF1_L)
line_HTF1_H := line.new(htf_candles_startingPos, iHighest, htf_candles_startingPos+1, iHighest, extend=extend.both, color=lineColor_1, style=lineStyle_1, width=lineWidth_1)
line_HTF1_L := line.new(htf_candles_startingPos, iLowest, htf_candles_startingPos+1, iLowest, extend=extend.both, color=lineColor_1, style=lineStyle_1, width=lineWidth_1)
if show_HTF2_Candles
line.delete(line_D_H_L)
line.delete(line_D_H_L_1)
line.delete(line_D_H_L_2)
line.delete(line_D_H_L_3)
line.delete(line_D_H_L_4)
line.delete(line_D_O_C)
line.delete(line_D_O_C_1)
line.delete(line_D_O_C_2)
line.delete(line_D_O_C_3)
line.delete(line_D_O_C_4)
label.delete(label_D_O)
label.delete(label_D_H)
label.delete(label_D_L)
label.delete(label_D_C)
label.delete(label_D_LL)
label.delete(label_D_RT)
line_D_H_L := line.new(htf_candles_startingPos + 92, DO_, htf_candles_startingPos + 92, DC_, color=(DO_<DC_?chart_color_up:DO_>DC_?chart_color_down:chart_color_even), width=9)
line_D_H_L_1 := line.new(htf_candles_startingPos + 89, DO_1, htf_candles_startingPos + 89, DC_1, color=(DO_1<DC_1?chart_color_up:DO_1>DC_1?chart_color_down:chart_color_even), width=9)
line_D_H_L_2 := line.new(htf_candles_startingPos + 86, DO_2, htf_candles_startingPos + 86, DC_2, color=(DO_2<DC_2?chart_color_up:DO_2>DC_2?chart_color_down:chart_color_even), width=9)
line_D_H_L_3 := line.new(htf_candles_startingPos + 83, DO_3, htf_candles_startingPos + 83, DC_3, color=(DO_3<DC_3?chart_color_up:DO_3>DC_3?chart_color_down:chart_color_even), width=9)
line_D_H_L_4 := line.new(htf_candles_startingPos + 80, DO_4, htf_candles_startingPos + 80, DC_4, color=(DO_4<DC_4?chart_color_up:DO_4>DC_4?chart_color_down:chart_color_even), width=9)
line_D_O_C := line.new(htf_candles_startingPos + 92, DH_, htf_candles_startingPos + 92, DL_, color=(O_<DC_?chart_color_up:DO_>DC_?chart_color_down:chart_color_even))
line_D_O_C_1 := line.new(htf_candles_startingPos + 89, DH_1, htf_candles_startingPos + 89, DL_1, color=(DO_1<DC_1?chart_color_up:DO_1>DC_1?chart_color_down:chart_color_even))
line_D_O_C_2 := line.new(htf_candles_startingPos + 86, DH_2, htf_candles_startingPos + 86, DL_2, color=(DO_2<DC_2?chart_color_up:DO_2>DC_2?chart_color_down:chart_color_even))
line_D_O_C_3 := line.new(htf_candles_startingPos + 83, DH_3, htf_candles_startingPos + 83, DL_3, color=(DO_3<DC_3?chart_color_up:DO_3>DC_3?chart_color_down:chart_color_even))
line_D_O_C_4 := line.new(htf_candles_startingPos + 80, DH_4, htf_candles_startingPos + 80, DL_4, color=(DO_4<DC_4?chart_color_up:DO_4>DC_4?chart_color_down:chart_color_even))
if show_HTF2_BOSlines
line.delete(line_HTF2_BOS_H0)
line.delete(line_HTF2_BOS_H1)
line.delete(line_HTF2_BOS_L0)
line.delete(line_HTF2_BOS_L1)
label.delete(label_D_BS_H)
label.delete(label_D_BS_L)
alert_HTF2_BOS_0 := false
alert_HTF2_BOS_1 := false
// 5個のローソク番号:[4][3][2][1][0]
// [4][3][2]のローソクから判定する
if DL_4>DL_3 and DL_3<DL_2
if DH_2<DC_1
// [2]と[1]でBOS発生してたらBOS引いてアラート設定
line_HTF2_BOS_H1 := line.new(htf_candles_startingPos + 86, DH_2, htf_candles_startingPos + 92, DH_2, color=line_color_BOS, width=line_width_BOS)
alert_HTF2_BOS_1 := true
// BOS label
if show_BOS_Labels
label.delete(label_D_BS_H)
label_D_BS_H := label.new(htf_candles_startingPos + 108, DH_2, text = "BOS: " + str.tostring(DH_2), textcolor=line_color_BOS, style=label.style_label_left, color = color.new(chart_color_even, 90))
else
// [2]と[1]でBOS発生してない場合はBOS候補の線(隣のBarまで延長)のみ引く
line_HTF2_BOS_H1 := line.new(htf_candles_startingPos + 86, DH_2, htf_candles_startingPos + 95, DH_2, color=line_color_BOS, width=line_width_BOS)
if DH_2<DC_
// [2]のBOS候補の線を[0]で抜いたらアラート設定
alert_HTF2_BOS_0 := true
// BOS label
if show_BOS_Labels
label.delete(label_D_BS_H)
label_D_BS_H := label.new(htf_candles_startingPos + 108, DH_2, text = "BOS: " + str.tostring(DH_2), textcolor=line_color_BOS, style=label.style_label_left, color = color.new(chart_color_even, 90))
if DH_4<DH_3 and DH_3>DH_2
if DL_2>DC_1
// [2]と[1]でBOS発生してたらBOS引いてアラート設定
line_HTF2_BOS_L1 := line.new(htf_candles_startingPos + 86, DL_2, htf_candles_startingPos + 92, DL_2, color=line_color_BOS, width=line_width_BOS)
alert_HTF2_BOS_1 := true
// BOS label
if show_BOS_Labels
label.delete(label_D_BS_L)
label_D_BS_L := label.new(htf_candles_startingPos + 108, DL_2, text = "BOS: " + str.tostring(DL_2), textcolor=line_color_BOS, style=label.style_label_left, color = color.new(chart_color_even, 90))
else
// [2]と[1]でBOS発生してない場合はBOS候補の線(隣のBarまで延長)のみ引く
line_HTF2_BOS_L1 := line.new(htf_candles_startingPos + 86, DL_2, htf_candles_startingPos + 95, DL_2, color=line_color_BOS, width=line_width_BOS)
if DL_2>DC_
// [2]のBOS候補の線を[0]で抜いたらアラート設定
alert_HTF2_BOS_0 := true
// BOS label
if show_BOS_Labels
label.delete(label_D_BS_L)
label_D_BS_L := label.new(htf_candles_startingPos + 108, DL_2, text = "BOS: " + str.tostring(DL_2), textcolor=line_color_BOS, style=label.style_label_left, color = color.new(chart_color_even, 90))
// [3][2][1]のローソクから判定する
if DL_3>DL_2 and DL_2<DL_1
line_HTF2_BOS_H0 := line.new(htf_candles_startingPos + 89, DH_1, htf_candles_startingPos + 95, DH_1, color=line_color_BOS, width=line_width_BOS)
if DH_1<DC_
// [1]のBOS候補の線を[0]で抜いたらアラート設定
alert_HTF2_BOS_0 := true
// BOS label
if show_BOS_Labels
label.delete(label_D_BS_H)
label_D_BS_H := label.new(htf_candles_startingPos + 108, DH_1, text = "BOS: " + str.tostring(DH_1), textcolor=line_color_BOS, style=label.style_label_left, color = color.new(chart_color_even, 90))
if DH_3<DH_2 and DH_2>DH_1
line_HTF2_BOS_L0 := line.new(htf_candles_startingPos + 89, DL_1, htf_candles_startingPos + 95, DL_1, color=line_color_BOS, width=line_width_BOS)
if DL_1>DC_
// [1]のBOS候補の線を[0]で抜いたらアラート設定
alert_HTF2_BOS_0 := true
// BOS label
if show_BOS_Labels
label.delete(label_D_BS_L)
label_D_BS_L := label.new(htf_candles_startingPos + 108, DL_1, text = "BOS: " + str.tostring(DL_1), textcolor=line_color_BOS, style=label.style_label_left, color = color.new(chart_color_even, 90))
if show_Labels
label_D_O := label.new(htf_candles_startingPos + 108, DO_, text = "O : " + str.tostring(DO_), textcolor=(DO_<DC_?chart_color_up:DO_>DC_?chart_color_down:chart_color_even), style=label.style_label_left, color = color.new(chart_color_even, 70))
label_D_H := label.new(htf_candles_startingPos + 93, DH_, text = "H : " + str.tostring(DH_), textcolor=(DO_<DC_?chart_color_up:DO_>DC_?chart_color_down:chart_color_even), style=label.style_label_left, color = color.new(chart_color_even, 70))
label_D_L := label.new(htf_candles_startingPos + 108, DL_, text = "L : " + str.tostring(DL_), textcolor=(DO_<DC_?chart_color_up:DO_>DC_?chart_color_down:chart_color_even), style=label.style_label_left, color = color.new(chart_color_even, 70))
label_D_C := label.new(htf_candles_startingPos + 93, DC_, text = "C : " + str.tostring(DC_), textcolor=(DO_<DC_?chart_color_up:DO_>DC_?chart_color_down:chart_color_even), style=label.style_label_left, color = color.new(chart_color_even, 70))
// [line_D_H_L,line_D_H_L_1,line_D_H_L_2,line_D_H_L_3,line_D_H_L_4, line_D_O_C,line_D_O_C_1,line_D_O_C_2,line_D_O_C_3,line_D_O_C_4, label_D_O, label_D_H, label_D_L, label_D_C, label_D_LL, label_D_RT]
iHighest = DH_
if iHighest < DH_1
iHighest := DH_1
if iHighest < DH_2
iHighest := DH_2
if iHighest < DH_3
iHighest := DH_3
if iHighest < DH_4
iHighest := DH_4
iLowest = DL_
if iLowest > DL_1
iLowest := DL_1
if iLowest > DL_2
iLowest := DL_2
if iLowest > DL_3
iLowest := DL_3
if iLowest > DL_4
iLowest := DL_4
if show_RemainTime
label_D_RT := label.new(htf_candles_startingPos + 100, iHighest, text = convert_mSecToTime(time_close(TF2)-timenow), textcolor=(DO_<DC_?chart_color_up:DO_>DC_?chart_color_down:chart_color_even), style=label.style_label_right, color = na, size=size.large)
label_D_LL := label.new(htf_candles_startingPos + 70, (DH_ + DL_)/2, text = "TF: " + str.tostring(TF2), textcolor=(DO_<DC_?chart_color_up:DO_>DC_?chart_color_down:chart_color_even), style=label.style_label_right, color = na, size=size.large)
if show_HLLines_2
line.delete(line_HTF2_H)
line.delete(line_HTF2_L)
line_HTF2_H := line.new(htf_candles_startingPos, iHighest, htf_candles_startingPos+1, iHighest, extend=extend.both, color=lineColor_2, style=lineStyle_2, width=lineWidth_2)
line_HTF2_L := line.new(htf_candles_startingPos, iLowest, htf_candles_startingPos+1, iLowest, extend=extend.both, color=lineColor_2, style=lineStyle_2, width=lineWidth_2)
alertcondition(alert_HTF1_BOS_0 , title='HTF1 detected BOS - Liquidity Sweep', message='Detected BOS Alert!! - Liquidity Sweep : Judged by the rightmore bar [HTF1]')
alertcondition(alert_HTF1_BOS_1 , title='HTF1 detected BOS - Candle Close', message='Detected BOS Alert!! - Candle Close : Judged by 2nd bar from the right [HTF1]')
alertcondition(alert_HTF2_BOS_0 , title='HTF2 detected BOS - Liquidity Sweep', message='Detected BOS Alert!! - Liquidity Sweep : Judged by the rightmore bar [HTF2]')
alertcondition(alert_HTF2_BOS_1 , title='HTF2 detected BOS - Candle Close', message='Detected BOS Alert!! - Candle Close : Judged by 2nd bar from the right [HTF2]')
|
Faytterro Oscillator | https://www.tradingview.com/script/J49ocpJR-Faytterro-Oscillator/ | faytterro | https://www.tradingview.com/u/faytterro/ | 514 | 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/
// © faytterro
//@version=5
indicator("Faytterro Oscillator", overlay=false, max_lines_count=500, max_bars_back = 500)
src=input(hlc3,title="source")
len=input.int(50,title="lenght", maxval=500)
c = input.color(color.rgb(0, 217, 255))
w = input.int(1, minval = 1)
cr(x, y) =>
z = 0.0
weight = 0.0
for i = 0 to y-1
z:=z + x[i]*((y-1)/2+1-math.abs(i-(y-1)/2))
z/(((y+1)/2)*(y+1)/2)
cr= cr(src,2*len-1)
hline(50)
width= 1 //input.int(1,"width", minval=1)
//plot(cr, color= #cf0202, linewidth=width,offset=-len+1)
h1=hline(70)
h2=hline(30)
fill(h1,h2, color = color.rgb(203, 21, 235, 90))
mult = 2//input.float(2.0, minval=0.001, maxval=50, title="StdDev")
dev = mult * ta.stdev(src, len)
upper = cr + cr(dev, 2*len-1)
lower = cr - cr(dev, 2*len-1)
v = 100*(src[len]-lower)/(upper-lower)
fd(x) =>
100-100/(math.pow(1+0.03,x-50)+1)
fdv = fd(v)
//plot(lower, color= color.rgb(137, 255, 97), offset=1-len, linewidth=2)
//plot(upper, color= color.rgb(255, 137, 137), offset=1-len, linewidth=2)
//plot(v, offset=-len, linewidth=width, color = color.rgb(0, 217, 255), editable = false)
plot(fdv, offset=-len, linewidth=w, color = c, editable = false, display = display.pane)
// extrapolation
diz = array.new_float(500)
var lin=array.new_line()
diz2 = array.new_float(500)
diz3 = array.new_float(500)
var lin2=array.new_line(0)
var lin3=array.new_line(0)
if barstate.islast
for k=0 to len-1
sum=0.0
dv=0.0
for i=0 to 2*len-2-k
sum +=(len-math.abs(len-1-k-i))*src[i]/(len*len-k*(k+1)/2)
dv +=(len-math.abs(len-1-k-i))*dev[i]/(len*len-k*(k+1)/2)
array.set(diz,k, sum + dv)
array.set(diz2,k, sum - dv)
for i=0 to (len-1)
array.push(lin3, line.new(na, na, na, na))
line.set_xy1(array.get(lin3,i), bar_index[len]+i, fd(100*(src[len-i]-array.get(diz2,math.max(i-1,0)))/(array.get(diz,math.max(i-1,0))-array.get(diz2,math.max(i-1,0)))))
line.set_xy2(array.get(lin3,i), bar_index[len]+i+1, fd(100*(src[len-i-1]-array.get(diz2,i))/(array.get(diz,i)-array.get(diz2,i))))
line.set_color(array.get(lin3,i), color.new(c,i*80/(len-1) ))
line.set_width(array.get(lin3,i),w)
buy= fd(100*(src-array.get(diz2,len-1))/(array.get(diz,len-1)-array.get(diz2,len-1)))>30 and fd(100*(src[1]-array.get(diz2,len-2))/(array.get(diz,len-2)-array.get(diz2,len-2)))<30
sell= fd(100*(src-array.get(diz2,len-1))/(array.get(diz,len-1)-array.get(diz2,len-1)))<70 and fd(100*(src[1]-array.get(diz2,len-2))/(array.get(diz,len-2)-array.get(diz2,len-2)))>70
//plot(fd(100*(src-array.get(diz2,len-1))/(array.get(diz,len-1)-array.get(diz2,len-1))))
//plot(fd(100*(src[1]-array.get(diz2,len-2))/(array.get(diz,len-2)-array.get(diz2,len-2))))
alertcondition(buy, "oversold", "this is just an early warning. In the next bars, the indicator will confirm or reject this signal. please take this into account when assessing your risk.")
alertcondition(sell, "overbought", "this is just an early warning. In the next bars, the indicator will confirm or reject this signal. please take this into account when assessing your risk.")
//barcolor(color = buy? color.green : sell? color.red : na)//fdv>70? color.rgb(255, 20, 20) : fdv<30? color.rgb(20, 255, 20) : na, offset = -len)
bgcolor(color = buy? color.green : sell? color.red : na)
//plotshape(fdv>70, "sell", shape.triangledown, location.abovebar, color.red, -len, "", color.rgb(0,0,0,100), true, size = size.tiny)
//plotshape(fdv<30, "buy", shape.triangleup, location.belowbar, color.green, -len, "", color.rgb(0,0,0,100), true, size = size.tiny)
ttk= input.bool(false ,title = "close warning")
var testTable = table.new(position = position.middle_right, columns = 1, rows = 1, bgcolor = color.rgb(255, 235, 59, 100), border_width = 1)
if barstate.islast
table.cell(table_id = testTable, column = 0, row = 0, text = "WARNİNG\n Transparent lines are repainted to a limited extent. \nThe lower the transparency, \nthe lower the chance of repainting. \nAfter the number of bars in the 'length' section have passed, \nthe repaint disappears completely. ", text_color = color.rgb(255,150,150,ttk? 1000 : 0))
plot(fd(100*(src-array.get(diz2,len-1))/(array.get(diz,len-1)-array.get(diz2,len-1))), color = color.new(c,100)) |
IC breakout | https://www.tradingview.com/script/9ncJLRFH-IC-breakout/ | svsomere | https://www.tradingview.com/u/svsomere/ | 40 | 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/
// © svsomere
//@version=5
indicator("IC breakout", overlay=true, max_labels_count = 500)
// Variables
breakoutText = ""
// Functions
updateBreakOutText(ICBreakLow, ICBreakHigh, previousHighLowRange, previousOpenCloseRange) =>
updatedText = ""
if ICBreakLow
updatedText := "IC Beakout Low\nPrev h/l %: " + str.tostring(previousHighLowRange * 100) + "\nPrev o/c %: " + str.tostring(previousOpenCloseRange * 100)
else if ICBreakHigh
updatedText := "IC breakout high\nPrev h/l %: " + str.tostring(previousHighLowRange * 100) + "\nPrev o/c %: " + str.tostring(previousOpenCloseRange * 100)
updatedText
// Inputs
maxHighLowPriceRange = input.float(2, title='Maximum high/low price range', minval=0, step=0.1, group="Price Range") / 100
maxOpenClosePriceRange = input.float(0.1, title='Maximum open/close price range', minval=0, step=0.01, group="Price Range") / 100
// Calculate the previous high/low price range
previousHighLowRange = (high[1] - low[1]) / low[1]
// Calculate the previous open/close price range
previousOpenCloseRange = 0.0
if (close[1] > open[1])
previousOpenCloseRange := (close[1] - open[1]) / open[1]
else
previousOpenCloseRange := (open[1] - close[1]) / close[1]
// Calculate if current price breaks low
priceBreaksDown = close < low[1]
// Calculate if current price breaks high
priceBreaksUp = close > high[1]
// Calculate if previous block was an indecision candle
indecisionCandle = (previousHighLowRange <= maxHighLowPriceRange) and (previousOpenCloseRange <= maxOpenClosePriceRange)
// Calculate if indecision candle and breakout to low
ICBreakLow = indecisionCandle and priceBreaksDown
// Calculate if indecision candle and breakout to high
ICBreakHigh = indecisionCandle and priceBreaksUp
// Update the label
breakoutText := updateBreakOutText(ICBreakLow, ICBreakHigh, previousHighLowRange, previousOpenCloseRange)
if ICBreakLow or ICBreakHigh
breakoutLabel = label.new(bar_index, low, text=breakoutText, style=label.style_label_up, color=color.new(color.orange, 0))
label.set_yloc(breakoutLabel, yloc.belowbar)
// Alerts
alertcondition(ICBreakLow, title="2. IC breakout low")
alertcondition(ICBreakHigh, title="3. IC breakout high")
alertcondition(ICBreakLow or ICBreakHigh, title="1. IC breakout high/low") |
NYSE & NASDAQ Advance Minus Decline Oscillator | https://www.tradingview.com/script/XCTjima3-NYSE-NASDAQ-Advance-Minus-Decline-Oscillator/ | All_Verklempt | https://www.tradingview.com/u/All_Verklempt/ | 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/
// © All_Verklempt
//@version=5
indicator("NYSE & NASDAQ Advance Minus Decline Oscillator", "Market A-D", format=format.price, precision=2, timeframe="", timeframe_gaps=true)
// Symbol Inputs
symbolInput01 = input.symbol("ADD", "NYSE")
symbolInput02 = input.symbol("ADDQ", "NASDAQ")
// Other Inputs
marketupper = 2000
marketlower = -2000
midline = plot(0, "Midline", color = #916cda, linewidth = 2)
// Symbol Calls
symbol01 = request.security(symbolInput01, timeframe.period, expression = close)
symbol02 = request.security(symbolInput02, timeframe.period, expression = close)
// Colors
colUp1 = symbol01 > 0 ? input.color(color.rgb(227,218,201), '', group= 'formula > 0', inline= 'up') :
input.color(color.rgb(165, 80, 98), '', group= 'formula < 0', inline= 'dn')
colDn1 = symbol01 > 0 ? input.color(color.rgb(165, 80, 98), '', group= 'formula > 0', inline= 'up') :
input.color(color.rgb(227,218,201), '', group= 'formula < 0', inline= 'dn')
colUp2 = symbol02 > 0 ? input.color(color.rgb(227,218,201), '', group= 'formula > 0', inline= 'up') :
input.color(color.rgb(145,108,218), '', group= 'formula < 0', inline= 'dn')
colDn2 = symbol02 > 0 ? input.color(color.rgb(145,108,218), '', group= 'formula > 0', inline= 'up') :
input.color(color.rgb(227,218,201), '', group= 'formula < 0', inline= 'dn')
//–––––––––––[ fill ]–––––––––––
// fill colour between lines 'formulaPlot' & 'centerPlot'
// if value (formula) > 0 -> top_value = 2000, bottom_value = 0, use colour set colUp
// if value (formula) < 0 -> top_value = 0, bottom_value = -2000, use colour set colDn
// Plot Information
plot1 = plot(symbol01, title="S01", color=#a55062, linewidth = 3)
plot2 = plot(symbol02, title="S02", color=#916cda, linewidth = 3)
// when formula moves between these limits, the color will change towards the upper or lower colour, dependable where formula is situated
fill(plot1, midline, symbol01 > 0 ? 2000 : 0, symbol01 > 0 ? 0: -2000, colUp1, colDn1)
fill(plot2, midline, symbol02 > 0 ? 2000 : 0, symbol02 > 0 ? 0: -2000, colUp2, colDn2)
|
ICT MTF FVG [MK] | https://www.tradingview.com/script/oL0slGQF-ICT-MTF-FVG-MK/ | malk1903 | https://www.tradingview.com/u/malk1903/ | 322 | 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/
//@malk1903
//@version=5
indicator(title='ICT MTF FVG [MK]', shorttitle = 'MTF FVG [MK]',overlay=true, max_boxes_count = 500, max_labels_count = 500)
var color red = #e91e63
var color green = #089981
len = 0
c = close
o = open[len]
plotcandle(o, o, c, c, title='Nogi', color=o < c ? color.new(green,80) : color.new(red,80), bordercolor=color.new(color.black,100))
grp_tfs_enabled = "ENABLED TIME FRAMES"
tfcstrg = "FVG Time Frame Fill Colors"
inSession = not na(time(timeframe.period, "0930-1600"))
MTFImb = input.bool(title= 'MTF FVGs', defval=true, group='Enable/Disable Section---------------------------------------------', inline = '00')
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////MTF FVGs
OnlyMktHrs = false
fmthds = "Body"
fvgmethod = fmthds == "Body" ? true : false
show_labels = true
show_timeonlabels = false
hoursOffsetInput = input.float(-5.0, "Timezone offset", minval = -12.0, maxval = 14.0, step = 0.5, group = 'MTF Fair Vaue Gaps--------------------------------------------------', inline ='1')
var msOffsetInput = hoursOffsetInput * 1000 * 60 * 60
label_shift = input.int(defval=10, minval=1, maxval=100, step=1, title="FVG Offset to Right", group = 'MTF Fair Vaue Gaps--------------------------------------------------', inline ='1')
labelcolor = input.color(defval=color.new(color.white,0), title="Label Color", group = 'MTF Fair Vaue Gaps--------------------------------------------------', inline ='1')
incursion_alerts = true
incursion_pct = 20
intrusion_percentage= incursion_pct / 100
mitiaction = "Normal"
mitigationaction = if (mitiaction == 'Normal')
1
else
if (mitiaction == 'Dynamic')
2
else
if (mitiaction == 'None')
3
else
4
nomiticolor = color.new(color.yellow,85)
nmc_trans = color.t(nomiticolor)
show_mitigated_text = false
mitig_type = "Wicks"
UseBodyForMitigation= mitig_type == "Body" ? true : false
entrychangecolor = input.bool(true,"Change FVG Color On Entry ",inline='3')
entry_bull_color = input.color(color.new(color.white,90),"Bull",inline='3')
entry_bear_color = input.color(color.new(color.white,90),"Bear",inline='3')
// ============================================ //
// FVG Time Frame inputs and settings
// ============================================ //
enable_current_timeframe = input.bool(false,"Chart",group = grp_tfs_enabled,inline="0")
enable_5min = input.bool(false,"5 Minute",group = grp_tfs_enabled,inline="0")
enable_10min = input.bool(false,"10 Minute",group = grp_tfs_enabled,inline="0")
enable_15min = input.bool(false,"15 Minute",group = grp_tfs_enabled,inline="0")
enable_30min = input.bool(false,"30 Minute",group = grp_tfs_enabled,inline="0")
enable_1hr = input.bool(true,"1 Hour",group = grp_tfs_enabled,inline="0")
enable_4hr = input.bool(true,"4 Hour",group = grp_tfs_enabled,inline="0")
enable_8hr = input.bool(false,"8 Hour",group = grp_tfs_enabled,inline="0")
enable_12hr = input.bool(false,"12 Hour",group = grp_tfs_enabled,inline="0")
enable_Daily = input.bool(true,"Daily",group = grp_tfs_enabled,inline="0")
enable_Week = input.bool(true,"Weekly",group = grp_tfs_enabled,inline="0")
enable_Month = input.bool(true,"Monthly",group = grp_tfs_enabled,inline="0")
current_timeframe = timeframe.period
var timestring = ""
if timeframe.isintraday
if str.tonumber(current_timeframe) > 59
timestring := str.tostring(str.tonumber(current_timeframe) / 60) + " Hr"
else
timestring := current_timeframe + " Min"
else if timeframe.isdaily
timestring := "Daily"
else if timeframe.isweekly
timestring := "Weekly"
else
timestring := "Monthly"
// ============================================ //
// FVG Supported Timeframe strings used for labels and alertcondition at end
// ============================================ //
currtfstring = timestring
// min5s = '5 Min'
// min10s = '10 Min'
// min15s = '15 Min'
// min1hrs = '1 Hr'
// min4hrs = '4 Hr'
// min8hrs = '8 Hr'
// minds = 'Daily'
// minws = 'Weekly'
// minms = 'Monthly'
maxgroup = "MAX FVGs SETTINGS (COMBINED MAXIMUM MUST BE LESS THAN 500)"
curr_MaxArraySize = input.int(8,"Chart",group = maxgroup,inline="0",minval = 1)
MaxArraySize_5min = input.int(8,"5 Min",group = maxgroup,inline="0",minval = 1)
MaxArraySize_10min = input.int(8,"10 Min",group = maxgroup,inline="0",minval = 1)
MaxArraySize_15min = input.int(8,"15 Min",group = maxgroup,inline="1",minval = 1)
MaxArraySize_30min = input.int(8,"30 Min",group = maxgroup,inline="1",minval = 1)
MaxArraySize_1hr = input.int(8,"1 Hr",group = maxgroup,inline="1",minval = 1)
MaxArraySize_4hr = input.int(8,"4 Hr",group = maxgroup,inline="2",minval = 1)
MaxArraySize_8hr = input.int(8,"8 Hr",group = maxgroup,inline="2",minval = 1)
MaxArraySize_12hr = input.int(8,"12 Hr",group = maxgroup,inline="2",minval = 1)
MaxArraySize_Daily = input.int(8,"Daily",group = maxgroup,inline="3",minval = 1)
MaxArraySize_Wkly = input.int(8,"Weekly",group = maxgroup,inline="3",minval = 1)
MaxArraySize_Mthly = input.int(8,"Monthly",group = maxgroup,inline="3",minval = 1)
//Create error box template (as table) if user entered over 500 fvgs total
var table ErrorBox = table.new(position.bottom_right, 1, 1, frame_color=color.red,frame_width = 1)
tot_user_max_boxes = curr_MaxArraySize + MaxArraySize_5min + MaxArraySize_10min + MaxArraySize_15min + MaxArraySize_1hr + MaxArraySize_4hr + MaxArraySize_8hr + MaxArraySize_Daily + MaxArraySize_Wkly + MaxArraySize_Mthly
isError = tot_user_max_boxes > 500
if isError
table.cell(ErrorBox, 0, 0, "MTF FVG INDICATOR ERROR\n\n"+"Max Number of FVGs exceeded, please change settings.", bgcolor = color.new(color.blue, 50),
text_color = color.red,text_halign=text.align_center)
bgcolor=color.new(color.maroon,90)
// SET DEFAULT COLORS FOR ALL TIMEFRAMES
bullfvgcolor = input.color(color.new(color.green,80),"Bull FVG Color",group = 'FVG BOX BORDER SETTINGS',inline='a')
bearfvgcolor = input.color(color.new(color.red,80),"Bear FVG Color",group = 'FVG BOX BORDER SETTINGS',inline='a')
// FVG Box Border Inputs
box_border_bull_color = (color.new(color.gray,100))
box_border_bear_color = (color.new(color.gray,100))
box_border_width = 1
bbstyle_string = "Solid"
box_border_style = line.style_dotted
boxrightfvg = true
// --------------------------------------------------------------- //
// | FUNCTIONS| //
// --------------------------------------------------------------- //
// simple strings required for request.security function in latter main code calls to handle_all function
_gettf_interval_str(simple int index) =>
string result = switch index
0 => "5"
1 => "10"
2 => "15"
3 => "30"
4 => "60"
5 => "240"
6 => "480"
7 => "720"
8 => "D"
9 => "W"
10 => "M"
=> "Unsupported Timeframe"
// simple strings require for label displays used in add_label ultimately
_gettf_label_str(simple int index) =>
string result = switch index
0 => "5 Min"
1 => "10 Min"
2 => "15 Min"
3 => "30 Min"
4 => "1 Hr"
5 => "4 Hr"
6 => "8 Hr"
7 => "12 Hr"
8 => "Daily"
9 => "Weekly"
10 => "Monthly"
=> "Unsupported Timeframe"
// used if user selected use chart timeframe option to see not double work if chart is set to same timeframe as another enabled timeframe for fvg creation
_not_current_timeframe_equal_enabled_tfs(_current_timeframe) =>
result = switch _current_timeframe
"5" => not enable_5min
"10" => not enable_10min
"15" => not enable_15min
"30" => not enable_30min
"60" => not enable_1hr
"240" => not enable_4hr
"480" => not enable_8hr
"720" => not enable_12hr
"D" => not enable_Daily
"W" => not enable_Week
"M" => not enable_Month
=> true
// ************* SEE IF NEW BULL FVGs DETECTED
_isfvgbull(_fvgmethod,_low,_high2,_close1,_open1) =>
if _fvgmethod // if body fvg detection
_low > _high2 and _low <= _close1 and _high2 > _open1
else // else wick detection
_high2 < _low
// ************* SEE IF NEW BEAR FVGs DETECTED
_isfvgbear(_fvgmethod,_low2,_high,_close1,_open1) =>
if _fvgmethod
_low2 > _high and _high >= _close1 and _low2 <= _open1
else
_low2 > _high
// *************** DELETE A BOX AND ASSOCIATED LABEL
_box_n_label_delete(_boxarray,_i,_labelarray,_labelflag) =>
bptr = array.get(_boxarray,_i)
box.delete(bptr)
array.remove(_boxarray, _i)
if _labelflag
lptr = array.get(_labelarray,_i)
label.delete(lptr)
array.remove(_labelarray,_i)
// *************** DELETE A MIDLINE
//_mline_deletebull(_linearray,_i) =>
//lnptr = array.get(_linearray,_i)
// line.delete(lnptr)
// array.remove(_linearray, _i)
//_mline_deletebear(_linearray2,_i) =>
// ln2ptr = array.get(_linearray2,_i)
// line.delete(ln2ptr)
// array.remove(_linearray2, _i)
//if _labelflag
//lptr = array.get(_labelarray,_i)
//label.delete(lptr)
//array.remove(_labelarray,_i)
// *************** GET A FVG BOX TOP AND BOTTOM VALUES
_getboxtopbtm(_boxptr,_i) =>
_boxelement = array.get(_boxptr,_i)
_top = box.get_top(_boxelement)
_btm = box.get_bottom(_boxelement)
[_boxelement,_top,_btm]
// *************** ADD A LABEL TO AN FVG
_addlabel(_fvglabelsarray,_bar_index,_high,_string,_style,y,_show_label) =>
var string s = na
if _show_label
if show_timeonlabels
s := _string + str.format(" {0,date,HH:mm MM/dd/yy}", time + msOffsetInput)
else
s := _string
blabel = label.new(_bar_index,_high,text=s,color=color.rgb(0,0,0,100),style = _style) //_string,color=color.rgb(0,0,0,100),style = _style)
label.set_textcolor(blabel,labelcolor)//color.rgb(label_red,label_grn,label_blu,label_trans))
label.set_xy(blabel,_bar_index + label_shift,y)
label.set_size(blabel,size.normal)
array.push(_fvglabelsarray,blabel)
// added these two globally as can't use them in functions with consistency/reliability towards incursion alerts
lasthigh = high[1]
lastlow = low[1]
// compare existing bull fvg box values to current price action
_getbullfvgaction(_top,_bottom,_intrusion_percentage) =>
midpt = (_top + _bottom) / 2
threshold = _top - (_intrusion_percentage * (_top - _bottom))
_have_intrusion = low < threshold and lastlow > threshold
_lowundertop = low < _top
_lowunderbtm = low < _bottom
_lowundermid = low < midpt
_closeundertop = close < _top
_closeunderbtm = close < _bottom
_closeundermid = low < midpt
[_lowundertop,_lowunderbtm,_closeundertop,_closeunderbtm,_lowundermid,_closeundermid,_have_intrusion]//,_closecrosswithin]
// compare existing bear fvg box values to current price action
_getbearfvgaction(_top,_bottom,_intrusion_percentage) =>
midpt = (_top + _bottom) / 2
//_have_intrusion = high > _bottom + (_intrusion_percentage * (_top - _bottom))
threshold = _bottom + (_intrusion_percentage * (_top - _bottom))
_have_intrusion = high > threshold and lasthigh < threshold
_highovertop = high > _top
_highoverbtm = high > _bottom
_highovermid = high > midpt
_closeovertop = close > _top
_closeoverbtm = close > _bottom
_closeovermid = close > midpt
[_highovertop,_highoverbtm,_closeovertop,_closeoverbtm,_highovermid,_closeovermid,_have_intrusion]
// used for adjusting fvg label position with each new bar
_setlabelxy(_fvglabels,_i,_barindex,_top,_bottom) =>
_lptr = array.get(_fvglabels,_i)
label.set_xy(_lptr,_barindex + label_shift,(_top + _bottom) / 2)
// used for adjusting bull box position with each new bar
_setboxleftbull(_boxbull,_i,_barindex) =>
_bxbull = box.get_left(_boxbull)
box.set_left(_boxbull,last_bar_index + label_shift)
// used for adjusting bear box position with each new bar
_setboxleftbear(_boxbear,_i,_barindex) =>
_bxbear = box.get_left(_boxbear)
box.set_left(_boxbear,last_bar_index + label_shift)
// get higher timeframe price values
_gethighlowcloseopens(_ticker,_period,_high,_high2,_low,_low2,_close1,_open1) =>
request.security(_ticker,_period,[_high,_high2,_low,_low2,_close1,_open1],lookahead = barmerge.lookahead_on)
var _bullmid = array.new_line()
var _bearmid = array.new_line()
var line bullmidl = na
var line bearmidl = na
// modify existing bull fvg boxes for incursion, deletion etc.
_update_bull_fvgs(_boxbull,_labelsbull,_timestring) =>
//var bool cclosecrosswithin = false
for i = array.size(_boxbull) - 1 to 0 by 1
[fvgboxbull,top,bottom] = _getboxtopbtm(_boxbull,i)
[lowundertop,lowunderbtm,closeundertop,closeunderbtm,lowundermid,closeundermid,intrusion] = _getbullfvgaction(top,bottom,intrusion_percentage)
// INCURSION ALERT DONE HERE: if mitigation action is normal or none then do alert
if (mitigationaction == 1 or mitigationaction == 3) and intrusion and incursion_alerts
alert("Bull FVG Incursion " + str.tostring(_timestring), alert.freq_once_per_bar)
if entrychangecolor
if lowundertop // low < top
box.set_bgcolor(fvgboxbull,entry_bull_color)
else
box.set_bgcolor(fvgboxbull,bullfvgcolor)
if show_labels
_setlabelxy(_labelsbull,i,bar_index,top,bottom)
_setboxleftbull(fvgboxbull,i,bar_index)
// *** if mitigation is set to dynamic and body is referenced with price and price is within fvg
if mitigationaction == 2 and UseBodyForMitigation and closeundertop
box.set_top(fvgboxbull,close)
if show_labels
_setlabelxy(_labelsbull,i,bar_index,close,bottom)
else
// else if mitigation set to dynamic and body mitigation NOT enabled and btm wick goes below top of fvg band then move band top lower
if mitigationaction == 2 and lowundertop
box.set_top(fvgboxbull,low)
if show_labels
_setlabelxy(_labelsbull,i,bar_index,low,bottom)
// section to delete boxes when fvg filled
if mitigationaction == 3 // if 'none' selected for mitigation
if UseBodyForMitigation and closeunderbtm
box.set_bgcolor(fvgboxbull,color.new(nomiticolor,nmc_trans))
else
if lowunderbtm
box.set_bgcolor(fvgboxbull,color.new(nomiticolor,nmc_trans))
if (UseBodyForMitigation and closeunderbtm) or lowunderbtm
if show_labels and show_mitigated_text
larray = array.get(_labelsbull,i)
curr_text = label.get_text(larray)
found = str.contains(curr_text,"Mitigated")
if not found
label.set_text(larray,curr_text + "Mitigated")
if mitigationaction == 1 or mitigationaction == 2
if UseBodyForMitigation and closeunderbtm
_box_n_label_delete(_boxbull, i,_labelsbull, show_labels)
// _mline_deletebull(_bullmid, i)
else
if lowunderbtm
_box_n_label_delete(_boxbull, i,_labelsbull, show_labels)
if mitigationaction == 4 // if half mitigation
if UseBodyForMitigation and closeundermid
_box_n_label_delete(_boxbull, i,_labelsbull, show_labels)
else
if lowundermid
_box_n_label_delete(_boxbull, i,_labelsbull, show_labels)
// modify existing bear fvg boxes for incursion, deletion etc.
_update_bear_fvgs(_boxbear,_labelsbear,_timestring) =>
for i = array.size(_boxbear) - 1 to 0 by 1
[fvgboxbear,top,bottom] = _getboxtopbtm(_boxbear,i)
[highovertop,highoverbtm,closeovertop,closeoverbtm,highovermid,closeovermid,intrusion] = _getbearfvgaction(top,bottom,intrusion_percentage)
// INCURSION ALERT DONE HERE: if mitigation action is normal or none then do alert
if (mitigationaction == 1 or mitigationaction == 3) and intrusion and incursion_alerts
alert("Bear FVG Incursion " + str.tostring(_timestring), alert.freq_once_per_bar)
if entrychangecolor
if highoverbtm
box.set_bgcolor(fvgboxbear,entry_bear_color)//color.new(bearfvgcolor,_bear_trans - (_bear_trans / 4)))
else
box.set_bgcolor(fvgboxbear,bearfvgcolor)//color.new(bearfvgcolor,_bear_trans))
if show_labels
_setlabelxy(_labelsbear,i,bar_index,top,bottom)
_setboxleftbear(fvgboxbear,i,bar_index)
// *** if mitigation is set to dynamic and body is referenced with price and price is within fvg
if mitigationaction == 2 and UseBodyForMitigation and closeoverbtm
box.set_bottom(fvgboxbear,close)
if show_labels
_setlabelxy(_labelsbear,i,bar_index,close,bottom)
else
// else if mitigation set to dynamic and body mitigation NOT enabled and top wick goes above bottom of fvg band then move band bottom up
if mitigationaction == 2 and highoverbtm
box.set_bottom(fvgboxbear,high)
if show_labels
_setlabelxy(_labelsbear,i,bar_index,top,high)
if mitigationaction == 3 // if 'none' selected for mitigation
if UseBodyForMitigation and closeovertop
box.set_bgcolor(fvgboxbear,color.new(nomiticolor,nmc_trans))
else
if highovertop
box.set_bgcolor(fvgboxbear,color.new(nomiticolor,nmc_trans))
if (UseBodyForMitigation and closeovertop) or highovertop
if show_labels and show_mitigated_text
larray = array.get(_labelsbear,i)
curr_text = label.get_text(larray)
found = str.contains(curr_text,"Mitigated")
if not found
label.set_text(larray,curr_text + "Mitigated")
if mitigationaction == 1 or mitigationaction == 2
if UseBodyForMitigation and closeovertop
_box_n_label_delete(_boxbear, i,_labelsbear, show_labels)
//_mline_deletebear(_bearmid, i)
else
if highovertop
_box_n_label_delete(_boxbear, i,_labelsbear, show_labels)
if mitigationaction == 4 // if half mitigation
if UseBodyForMitigation and closeovermid
_box_n_label_delete(_boxbear, i,_labelsbear, show_labels)
else
if highovermid
_box_n_label_delete(_boxbear, i,_labelsbear, show_labels)
// main function call here - detects and calls to create fvg boxes then calls the update fvg functions for bulls and bears fvgs for already existing fvg boxes
_handle_all(_tstring,_bullfvgs,_bearfvgs,_bulllabels,_bearlabels,_maxarraysize,_high,_highback2,_low,_lowback2,_closeback1,_openback1) =>
var bool _newBull = false
var bool _newBear = false
if OnlyMktHrs and inSession or not OnlyMktHrs
_newBull := _isfvgbull(fvgmethod,_low,_highback2,_closeback1,_openback1)
_newBear := _isfvgbear(fvgmethod,_lowback2,_high,_closeback1,_openback1)
if _newBull //and barstate.isconfirmed
if array.size(_bullfvgs) > _maxarraysize
_box_n_label_delete(_bullfvgs, 0,_bulllabels, show_labels)
if _highback2 != _highback2[1] and _low != _low[1]
array.push(_bullfvgs, box.new(left=last_bar_index + 20, bottom=_highback2, right=last_bar_index + 100, top=_low, bgcolor=bullfvgcolor, border_color=box_border_bull_color, border_width = box_border_width, border_style = box_border_style, extend=extend.right,text_halign = text.align_center, xloc = xloc.bar_index))
//array.push(_bullmid, line.new(x1=boxrightfvg ? last_bar_index + 1 : bar_index[2],y1=(_low+_highback2)/2,x2=boxrightfvg ? last_bar_index + 2 : last_bar_index + 1,y2=(_low+_highback2)/2, style=line.style_solid, color=color.white, width=1, extend=extend.right))
//array.push(_bullmid,bullmidl)
if show_labels
_addlabel(_bulllabels,bar_index,_high,_tstring + " FVG",label.style_label_left,(_high[2] + _low) / 2, show_labels)
if _newBear //and barstate.isconfirmed
if array.size(_bearfvgs) > _maxarraysize
_box_n_label_delete(_bearfvgs, 0,_bearlabels, show_labels)
if _lowback2 != _lowback2[1] and _high != _high[1]
array.push(_bearfvgs, box.new(left=last_bar_index + 20, top=_lowback2, right= last_bar_index + 100, bottom=_high, bgcolor=bearfvgcolor, border_color=box_border_bear_color, border_width = box_border_width, border_style = box_border_style, extend=extend.right,text_halign = text.align_center, xloc=xloc.bar_index))
//array.push(_bearmid, line.new(x1=boxrightfvg ? last_bar_index + 1 : bar_index[2],y1=(_lowback2+_high)/2,x2=boxrightfvg ? last_bar_index + 2 : last_bar_index + 1,y2=(_lowback2+_high)/2, style=line.style_solid, color=color.white, width=1, extend=extend.right))
//array.push(_bearmid,bearmidl)
if show_labels
_addlabel(_bearlabels,bar_index,_high,_tstring + " FVG",boxrightfvg ? label.style_label_left : label.style_label_right,(_high[2] + _low) / 2, show_labels)
//| BULL FVG HANDLING AREA | //
// ----------------------------------------------- //
if array.size(_bullfvgs) > 0 // this code is to handle incursion alerts before FVG's possibly being mitigated
_update_bull_fvgs(_bullfvgs,_bulllabels,_tstring)
// ----------------------------------------------- //
// | BEAR FVG HANDLING AREA | //
// ----------------------------------------------- //
if array.size(_bearfvgs) > 0 // this code is to handle incursion alerts before FVG's possibly being mitigated
_update_bear_fvgs(_bearfvgs,_bearlabels,_tstring)
// ***************************************************
// Array and Box definition area
// ***************************************************
var box[] fvgboxBull = array.new_box()
var box[] fvgboxBear = array.new_box()
var fvglabelsBull = array.new_label()
var fvglabelsBear = array.new_label()
var bool newboxBull = false
var bool newboxBear = false
var box[] fvgboxBull5 = array.new_box()
var box[] fvgboxBear5 = array.new_box()
var fvglabelsBull5 = array.new_label()
var fvglabelsBear5 = array.new_label()
var bool newboxBull5 = false
var bool newboxBear5 = false
var box[] fvgboxBull10 = array.new_box()
var box[] fvgboxBear10 = array.new_box()
var fvglabelsBull10 = array.new_label()
var fvglabelsBear10 = array.new_label()
var bool newboxBull10 = false
var bool newboxBear10 = false
var box[] fvgboxBull15 = array.new_box()
var box[] fvgboxBear15 = array.new_box()
var fvglabelsBull15 = array.new_label()
var fvglabelsBear15 = array.new_label()
var bool newboxBull15 = false
var bool newboxBear15 = false
var box[] fvgboxBull30 = array.new_box()
var box[] fvgboxBear30 = array.new_box()
var fvglabelsBull30 = array.new_label()
var fvglabelsBear30 = array.new_label()
var bool newboxBull30 = false
var bool newboxBear30 = false
var box[] fvgboxBull1hr = array.new_box()
var box[] fvgboxBear1hr = array.new_box()
var fvglabelsBull1hr= array.new_label()
var fvglabelsBear1hr= array.new_label()
var bool newboxBull1hr = false
var bool newboxBear1hr = false
var box[] fvgboxBull4hr = array.new_box()
var box[] fvgboxBear4hr = array.new_box()
var fvglabelsBull4hr= array.new_label()
var fvglabelsBear4hr= array.new_label()
var bool newboxBull4hr = false
var bool newboxBear4hr = false
var box[] fvgboxBull8hr = array.new_box()
var box[] fvgboxBear8hr = array.new_box()
var bool newboxBull8hr = false
var bool newboxBear8hr = false
var fvglabelsBull8hr= array.new_label()
var fvglabelsBear8hr= array.new_label()
var box[] fvgboxBull12hr = array.new_box()
var box[] fvgboxBear12hr = array.new_box()
var bool newboxBull12hr = false
var bool newboxBear12hr = false
var fvglabelsBull12hr= array.new_label()
var fvglabelsBear12hr= array.new_label()
var box[] fvgboxBullDaily = array.new_box()
var box[] fvgboxBearDaily = array.new_box()
var fvglabelsBullDaily = array.new_label()
var fvglabelsBearDaily = array.new_label()
var bool newboxBullDaily = false
var bool newboxBearDaily = false
var box[] fvgboxBullWeekly = array.new_box()
var box[] fvgboxBearWeekly = array.new_box()
var fvglabelsBullWeekly = array.new_label()
var fvglabelsBearWeekly = array.new_label()
var bool newboxBullWeekly = false
var bool newboxBearWeekly = false
var box[] fvgboxBullMonthly = array.new_box()
var box[] fvgboxBearMonthly = array.new_box()
var fvglabelsBullMonthly = array.new_label()
var fvglabelsBearMonthly = array.new_label()
var bool newboxBullMonthly = false
var bool newboxBearMonthly = false
//
///////////////////////////////////////
//| MAIN CODE |
///////////////////////////////////////
if enable_current_timeframe and _not_current_timeframe_equal_enabled_tfs(current_timeframe) and MTFImb
[_high,highback2,_low,lowback2,closeback1,openback1] = _gethighlowcloseopens(syminfo.tickerid,current_timeframe,high[1],high[3],low[1],low[3],close[2],open[2])
_handle_all(currtfstring,fvgboxBull,fvgboxBear,fvglabelsBull,fvglabelsBear,curr_MaxArraySize,_high,highback2,_low,lowback2,closeback1,openback1)
if enable_5min and MTFImb
[_high,highback2,_low,lowback2,closeback1,openback1] = _gethighlowcloseopens(syminfo.tickerid,_gettf_interval_str(0),high[1],high[3],low[1],low[3],close[2],open[2])
_handle_all(_gettf_label_str(0),fvgboxBull5,fvgboxBear5,fvglabelsBull5,fvglabelsBear5,MaxArraySize_5min,_high,highback2,_low,lowback2,closeback1,openback1)
if enable_10min and MTFImb
[_high,highback2,_low,lowback2,closeback1,openback1] = _gethighlowcloseopens(syminfo.tickerid,_gettf_interval_str(1),high[1],high[3],low[1],low[3],close[2],open[2])
_handle_all(_gettf_label_str(1),fvgboxBull10,fvgboxBear10,fvglabelsBull10,fvglabelsBear10,MaxArraySize_10min,_high,highback2,_low,lowback2,closeback1,openback1)
if enable_15min and MTFImb
[_high,highback2,_low,lowback2,closeback1,openback1] = _gethighlowcloseopens(syminfo.tickerid,_gettf_interval_str(2),high[1],high[3],low[1],low[3],close[2],open[2])
_handle_all(_gettf_label_str(2),fvgboxBull15,fvgboxBear15,fvglabelsBull15,fvglabelsBear15,MaxArraySize_15min,_high,highback2,_low,lowback2,closeback1,openback1)
if enable_30min and MTFImb
[_high,highback2,_low,lowback2,closeback1,openback1] = _gethighlowcloseopens(syminfo.tickerid,_gettf_interval_str(3),high[1],high[3],low[1],low[3],close[2],open[2])
_handle_all(_gettf_label_str(3),fvgboxBull30,fvgboxBear30,fvglabelsBull30,fvglabelsBear30,MaxArraySize_30min,_high,highback2,_low,lowback2,closeback1,openback1)
if enable_1hr and MTFImb
[_high,highback2,_low,lowback2,closeback1,openback1] = _gethighlowcloseopens(syminfo.tickerid,_gettf_interval_str(4),high[1],high[3],low[1],low[3],close[2],open[2])
_handle_all(_gettf_label_str(4),fvgboxBull1hr,fvgboxBear1hr,fvglabelsBull1hr,fvglabelsBear1hr,MaxArraySize_1hr,_high,highback2,_low,lowback2,closeback1,openback1)
if enable_4hr and MTFImb
[_high,highback2,_low,lowback2,closeback1,openback1] = _gethighlowcloseopens(syminfo.tickerid,_gettf_interval_str(5),high[1],high[3],low[1],low[3],close[2],open[2])
_handle_all(_gettf_label_str(5),fvgboxBull4hr,fvgboxBear4hr,fvglabelsBull4hr,fvglabelsBear4hr,MaxArraySize_4hr,_high,highback2,_low,lowback2,closeback1,openback1)
if enable_8hr and MTFImb
[_high,highback2,_low,lowback2,closeback1,openback1] = _gethighlowcloseopens(syminfo.tickerid,_gettf_interval_str(6),high[1],high[3],low[1],low[3],close[2],open[2])
_handle_all(_gettf_label_str(6),fvgboxBull8hr,fvgboxBear8hr,fvglabelsBull8hr,fvglabelsBear8hr,MaxArraySize_8hr,_high,highback2,_low,lowback2,closeback1,openback1)
if enable_12hr and MTFImb
[_high,highback2,_low,lowback2,closeback1,openback1] = _gethighlowcloseopens(syminfo.tickerid,_gettf_interval_str(7),high[1],high[3],low[1],low[3],close[2],open[2])
_handle_all(_gettf_label_str(7),fvgboxBull12hr,fvgboxBear8hr,fvglabelsBull12hr,fvglabelsBear12hr,MaxArraySize_12hr,_high,highback2,_low,lowback2,closeback1,openback1)
if enable_Daily and MTFImb
[_high,highback2,_low,lowback2,closeback1,openback1] = _gethighlowcloseopens(syminfo.tickerid,_gettf_interval_str(8),high[1],high[3],low[1],low[3],close[2],open[2])
_handle_all(_gettf_label_str(8),fvgboxBullDaily,fvgboxBearDaily,fvglabelsBullDaily,fvglabelsBearDaily,MaxArraySize_Daily,_high,highback2,_low,lowback2,closeback1,openback1)
if enable_Week and MTFImb
[_high,highback2,_low,lowback2,closeback1,openback1] = _gethighlowcloseopens(syminfo.tickerid,_gettf_interval_str(9),high[1],high[3],low[1],low[3],close[2],open[2])
_handle_all(_gettf_label_str(9),fvgboxBullWeekly,fvgboxBearWeekly,fvglabelsBullWeekly,fvglabelsBearWeekly,MaxArraySize_Wkly,_high,highback2,_low,lowback2,closeback1,openback1)
if enable_Month and MTFImb
[_high,highback2,_low,lowback2,closeback1,openback1] = _gethighlowcloseopens(syminfo.tickerid,_gettf_interval_str(10),high[1],high[3],low[1],low[3],close[2],open[2])
_handle_all(_gettf_label_str(10),fvgboxBullMonthly,fvgboxBearMonthly,fvglabelsBullMonthly,fvglabelsBearMonthly,MaxArraySize_Mthly,_high,highback2,_low,lowback2,closeback1,openback1)
// // ------------------------------------------------------- //
// // | STANDARD CONDITIONAL ALERT SECTION | //
// // ------------------------------------------------------- //
bull_fvg_creation_alert = newboxBull or newboxBull5 or newboxBull10 or newboxBull15 or newboxBull1hr or newboxBull4hr or newboxBull8hr or newboxBullDaily or newboxBullWeekly or newboxBullMonthly
alertcondition(bull_fvg_creation_alert,title='Bull FVG Creation',message = 'Bull FVG Creation' )
bear_fvg_creation_alert = newboxBear or newboxBear5 or newboxBear10 or newboxBear15 or newboxBear1hr or newboxBear4hr or newboxBear8hr or newboxBearDaily or newboxBearWeekly or newboxBearMonthly
alertcondition(bear_fvg_creation_alert,title='Bear FVG Creation',message = 'Bear FVG Creation' )
both_fvg_creation_alert = newboxBull or newboxBull5 or newboxBull10 or newboxBull15 or newboxBull1hr or newboxBull4hr or newboxBull8hr or newboxBullDaily or newboxBullWeekly or newboxBullMonthly or newboxBear or newboxBear5 or newboxBear10 or newboxBear15 or newboxBear1hr or newboxBear4hr or newboxBear8hr or newboxBearDaily or newboxBearWeekly or newboxBearMonthly
alertcondition(both_fvg_creation_alert,title='Both Bull or Bear FVG Creations',message = 'Both Bull or Bear FVG Creations' ) |
Weis V5 zigzag jayy | https://www.tradingview.com/script/Q9yRc4Ss-Weis-V5-zigzag-jayy/ | jayy | https://www.tradingview.com/u/jayy/ | 97 | 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/
// © jayy
//@version=5
//First published privately April 22, 2021 https://www.tradingview.com/script/jrZQBZ5D-Weis-zigzag-v4-jayy/
// v5 published privately Feb 2, 2022
// Somehow, I deleted version 5 of the zigzag script. Same name. I have added some older notes describing how the Weis Wave works.
// I have also changed the date restriction that stopped the script from working after Dec 31, 2022.
// What you see here is the Weis zigzag wave plotted directly on the price chart. This script is the companion to the Weis cumulative wave volume script.
// What is a Weis wave? David Weis has been recognized as a Wyckoff method analyst he has written two books one of which, Trades About to Happen,
// describes the evolution of the now-popular Weis wave. The method employed by Weis is to identify waves of price action and to compare the strength of
// the waves on characteristics of wave strength. Chief among the characteristics of strength is the cumulative volume of the wave.
// There are other markers that Weis uses as well for example how the actual price difference between the start of the Weis wave from start to finish. Weis also uses time,
// particularly when using a Renko chart
// David Weis did a futures io video which is a popular source of information about his method. (Search David Weis and futures.io. I strongly suggest you also read “Trades About to Happen”
// by David Weis.
// This will get you up and running more quickly when studying charts. However, you should choose the Traditional method to be true to David Weis technique as described in his book
// "Trades About to Happen" and in the Futures IO Webcast featuring David Weis
// https://www.tradingview.com/script/k4X18NJK-Weis-Pip-Wave-jayy/ .
// The Weis pip zigzag wave shows how far in terms of bar close price a Weis wave has traveled through the duration of a Weis wave. The Weis zigzag wave is used in combination with the
// Weis cumulative volume wave. The two waves should be set to the same "wave size".
// To use this script, you must set the wave size: Using the traditional Weis method simply enter the desired wave size in the box "How should wave size be calculated",
// in this example I am using a traditional wave size of .25. Each wave for each security and each timeframe requires its own wave size. Although not the traditional method devised
// by David Weis a more automatic way to set wave size would be to use Average True Range (ATR). Using ATR is not the true Weis method but it does give you similar waves and, importantly,
// without the hassle described above. Once the Weis wave size is set then the zigzag wave will be shown with volume. Because Weis used the closing price of a wave to define waves a
// line Bar highs and bar lows are not captured by the Weis Wave. The default script setting is now cumulative volume waves using an ATR of 7 and a multiplication factor of .5.
// To display volume in a way that does not crowd out neighbouring volumes Weis displayed volume as a maximum of 3 digits (usually). Consider two Weis Wave volumes
// 176,895,570 and 2,654,763,889. To display wave volume as three digits it is necessary to take a number such as 176,895,570 and truncate it. 176,895,570 can be represented as
// 177 X 10 to the power of 6. The number displayed must also be relative to other numbers in the field. If the highest volume on the page is: 2,654,763,889 and with only three
// numbers available to display the result the value shown must be 265 (265 X 10 to the power of 7). Since 176,895,570 is an order of magnitude smaller than 2,654,763,889 therefore
// 175,895,570 must be shown as 18 instead of 177. In this way, the relative magnitudes of the two volumes can be understood. All numbers in the field of view must be truncated by the
// same order of magnitude to make the relative volumes understandable. The script attempts to calculate the order of magnitude value automatically. If you see a red number in the field
// of view it means the script has failed to do the calculation automatically and you should use the manual method – use the dialogue box “Calculate truncated wave value automatically or manually”.
// Scroll down from the automatic method and select manual. Once "manual" is selected the values displayed become the power values or multipliers for each wave.
// Using the manual method you will select a “Multiplier” in the next dialogue box. Scan the field and select the largest value in the field of view (visible chart) is the multiplier of interest.
// If you select a lower number than the maximum value will see at least one red “up”. If you are too high you will see at least one red “down”. Scroll in the direction recommended or the
// values on the screen will be totally incorrect. With volume truncated to the highest order values, the eye can quickly get a feel for relative volumes. It also reduces the crowding and
// overlapping of values on the screen. You can opt to show the full volume to help get a sense of the magnitude of the true volumes.
// How does the script determine if a Weis wave is continuing to grow or not?
// The script evaluates the closing price of each new bar relative to the "Weis wave size". Suppose the current bar closes at a new low close, within the current down wave, at $30.00.
// If the Weis wave size is $0.10 then the algorithm will remember the $30.00 close and compare it to the close of the next bar. If the bar close price does not close equal to or lower
// than $30.00 or close equal to or higher than $30.10 then the wave is still a down wave with a current low of $30.00. This is true even if the bar low is less than $30.00 or the bar
// high is greater than 30.10 – only the bar’s closing price matters. If a bar's closing price climbs back up to a close of $30.11 then because the closing price has moved more than $0.10
// (the Weis wave size) then that is a wave reversal with a new up-trending wave. In the above example if there was currently a downward trending wave and the bar closes were as follows $30.00,
// $30.09, $30.01, $30.05, $30.10 The wave direction would continue to stay downward trending until the close of $30.10 was achieved. As such $30.00 would be the low and the following closes
// $30.09, $30.01, $30.05 would be allocated to the new upward-trending wave. If however There was a series of bar closes like this $30.00, $30.09, $30.01, $30.05, $29.99 since none of the closes
// was equal to above the 10-cent reversal target of $30.10 but instead, a new Weis wave low was achieved ($29.99). As such the closes of $30.09, $30.01, $30.05 would all be attributed to the
// continued down-trending wave with a current low of $29.99, even though the closing price for the interim bars was above $30.00. Now that the Weis Wave low is now 429.99 then, in order to
// reverse this continued downtrend price will need to close at or above $30.09 on subsequent bar closes assuming now new low bar close is achieved. With large wave sizes, wave direction can be
// in limbo for many bars before a close either renews wave direction or reverses it and confirms wave direction as either a reversal or a continuation. On the zig-zag, a wave line and its volume
// will not be "printed" until a wave reversal is confirmed.
// The wave attribution is similar when using other methods to define wave size. If ATR is used for wave size instead of a traditional wave constant size such as $0.10 or $2 or 2000 pips or ...
// then the wave size is calculated based on current ATR instead of the Weis wave constant (Traditional selected value).
// I have the option to display pseudo-Ord volume. In truth, Ord used more traditional zig-zag pivots of bar highs and lows. Waves using closes as pivots can have some significant differences.
// This difference can be lessened by using smaller time frames and larger wave sizes.
// There other options such to display the delta price or pip size of a Weis Wave, the number of bars in a wave
indicator('Weis V5 zigzag jayy', overlay=true, max_labels_count=500, max_lines_count=500, max_bars_back=4999)
shokey = input(false, title='Show key variables after last bar')
KO = time > timestamp(syminfo.timezone, 2032, 12, 31, 23, 59) ? false : true
//KO=time>timestamp(syminfo.timezone, 2021, 04, 09, 12, 48)?false:true
wavechoice_ = input.string(title='Choose wave type, default is cumulative volume, try Weis cumulative volume/delta price to help identify change of behaviour ', defval='Weis volume', options=['Weis volume', 'delta price or delta pip', 'wave time - time based charts only', 'Weis cumulative volume/delta price', 'pseudo-Ord volume', 'Weis volume and # bars per wave', 'Weis wave volume and Ord volume'])
// sensitivity_= input(title="calculate truncated wave value automatically or manually, any red numbers means the manual method must be used or try a different sensitivity", defval="Automatically calculate", options=["Automatically calculate",
// "Manually set multiplier","sensitivity 1", " sensitivity 2", " sensitivity 3"])
// calcmult_a=sensitivity_=="Calculate automatically"?4:sensitivity_=="Manually set multiplier"?5:sensitivity_=="sensitivity 1"?1: sensitivity_==" sensitivity 2"?2:sensitivity_== " sensitivity 3"?3:na
sensitivity_ = input.string(title='calculate truncated wave value automatically or manually, any red numbers means the manual method must be used or try a different sensitivity', defval='Automatically calculate', options=['Automatically calculate', 'Manually set multiplier', 'sensitivity 1', ' sensitivity 2', ' sensitivity 3', 'alternative auto method'])
calcmult_a = sensitivity_ == 'Calculate automatically' ? 4 : sensitivity_ == 'Manually set multiplier' ? 5 : sensitivity_ == 'sensitivity 1' ? 1 : sensitivity_ == ' sensitivity 2' ? 2 : sensitivity_ == ' sensitivity 3' ? 3 : sensitivity_ == 'alternative auto method' ? 6 : na
// sensitivity_= input(title="calculate truncated wave value automatically or manually, any red numbers means the manual method must be used or try a different sensitivity", defval="Automatically calculate", options=["Automatically calculate",
// "Manually set multiplier","Automatic X 10", "Automatic X 100", "Automatic X 0.1", "alternative auto method","alternative auto method x10" ])
// calcmult_a=sensitivity_=="Calculate automatically"?4:sensitivity_=="Manually set multiplier"?5:sensitivity_=="Automatic X 10"?1: sensitivity_=="Automatic X 100"?2:
// sensitivity_== "Automatic X 0.1"?3:sensitivity_== "alternative auto method"?6:sensitivity_== "alternative auto method x10"?7: na
shovol_ = input.string(title='Show volume in the truncated way Weis did, show actual volume or hide volume', defval='Weis truncated volume', options=['Weis truncated volume', 'Show true wave volume', 'Show waves without volume', 'Automatic X 10', 'Automatic X 100', 'Automatic X 0.1', 'Automatic X 0.01'])
// shovol_= input(title="Show volume in the truncated way Weis did, show actual volume or hide volume", defval="Weis truncated volume",
// options=["Weis truncated volume", "Show true wave volume","Show waves without volume" ]) //,"Automatic X 10", "Automatic X 100", "Automatic X 0.1"
shovol = shovol_ == 'Show waves without volume' ? false : true // input(true, title="show volume?")
//calcmult = calcmult_a==5 or calcmult_a==6 or calcmult_a==7?false:true //if manual method is selected then calcmult will be false ie auto method when calcmult is true
calcmult = calcmult_a == 5 ? false : true
mul = input.int(0, minval=-12, title='Multiplier: Manual method increase to highest multiplier on waves shown when 0 displayed here. or hit up arrow then follow up or down instructions.')
mult = mul >= 1 or mul < 0 ? mul : na
wavecalc = input.string(title='How should wave size be defined and calculated, default is ATR for quick set up. Use traditional for the true David Weis method', defval='Average true range and multiplier', options=['traditional Weis wave size ie price', 'Average true range and multiplier', 'percent of last leg', ' percent of average price'])
minrang = input(.05000000000000, title='Select traditional Weis wave size, to ball park try 1/1000th of price then scale up or down by factors of 10 ')
truerange = wavecalc == 'Average true range and multiplier' ? true : false // input(true, title="Use average true range?")
trralength = input.int(7, minval=2, title='Average true range length, larger values will smooth out the wave to wave variations of wave confirmation points. Try 7 or 70')
treafactor = input(.5000, title='Average true range multiple factor adjusts the wave size to pick up or eliminate smaller price moves')
percentw = wavecalc == 'percent of last leg' ? true : false // input(false, title="Use percent of last leg?")
percent = input(9.000, title='What percent of last leg to determine reverse')
minrangpw = wavecalc == ' percent of average price' ? true : false // input(false, title="Use percent of avg price to set wave size")
minrangprice = input(5.000, title='What percent of avg price to set wave size. The value can vary widely from small fractions of a percent to 10% or more. This zigzag is close to close not high to low')
minrangp = minrangprice / 100
//sensitivity = calcmult_a==1?1:calcmult_a==1?1:calcmult_a==1?1:0 //input(0, title="sensitivity of the automatic wave volume calculator 1 is high sensitivity, 2 medium and three low sensitivity", minval=0, maxval=3)
sensitivity = calcmult_a == 1 ? 1 : calcmult_a == 2 ? 2 : calcmult_a == 3 ? 3 : 0
rf = input.int(0, minval=0, maxval=8, title='Move wave labels away from bars?')
linewidth = input.int(1, 'Wave Line Width', minval=1, maxval=5)
ts = input.string(title='Text size, auto does not seem to work', defval='normal', options=['tiny', 'small', 'normal', 'large', 'huge', 'auto'])
oldwave = input(false, title='show Pinescript Version 1 wave')
showweiswave = input(false, title='Show Version 3 weis wave (lagged pivots) unclick to show the pinescript V1 no lag version?')
colorb = input(title='Colour of text', defval=color.black)
colorr = input(title='Colour of text when warning of need to manually calculate mult factor', defval=color.red)
colorc = input(title='Colour of actual vol delta price and # bars', defval=color.navy)
colourupwave = input(title='Colour of up wave', defval=color.black)
colourdownwave = input(title='Colour of down wave', defval=color.black)
//size_=input(title="size of text", type=input=label.set.size, defval=size.auto)
pricehloc = input(title='Source, almost always it should be left as the default: close', defval=close)
//rf= input(0,minval=0, maxval=8, title="Move wave labels away from bars?")
wavechoice = wavechoice_ == 'Weis volume' ? 1 : wavechoice_ == 'delta price or delta pip' ? 2 : wavechoice_ == 'wave time - time based charts only' ? 3 : wavechoice_ == 'Weis cumulative volume/delta price' ? 4 : wavechoice_ == 'Ord volume' ? 5 : wavechoice_ == 'Weis volume and # bars per wave' ? 6 : wavechoice_ == 'Weis wave volume and Ord volume' ? 7 : na // ord style vol per bar for each wave
//wavechoice:=wavechoice==5 or wavechoice==6?1:wavechoice
avspread = false //input(false, title= "Use avg high low spread?")
spreadlength = 10 //input(10, title= "Average Spread length")
spreadfactor = .5 //input(.5, title= "Multiple of spread factor")
trange = treafactor * ta.atr(trralength)
minrangetr = spreadfactor * ta.ema(high - low, spreadlength)
var count = 0
count := nz(count[1]) + 1
tickid = ticker.new(syminfo.prefix, syminfo.ticker, session.regular)
dopen = request.security(syminfo.tickerid, 'D', open)
sma_1 = ta.sma(close, 1)
sma_2 = ta.sma(close, 2)
sma_3 = ta.sma(close, 3)
sma_4 = ta.sma(close, 4)
sma_5 = ta.sma(close, 5)
sma_6 = ta.sma(close, 6)
sma_7 = ta.sma(close, 7)
sma_8 = ta.sma(close, 8)
sma_9 = ta.sma(close, 9)
sma_10 = ta.sma(close, 10)
sma_11 = ta.sma(close, 11)
sma_12 = ta.sma(close, 13)
sma_13 = ta.sma(close, 14)
sma_14 = ta.sma(close, 15)
sma_15 = ta.sma(close, 16)
sma_16 = ta.sma(close, 17)
sma_17 = ta.sma(close, 18)
sma_18 = ta.sma(close, 19)
sma_19 = ta.sma(close, 20)
avgprice = count == 1 ? sma_1 : count == 2 ? sma_2 : count == 3 ? sma_3 : count == 4 ? sma_4 : count == 5 ? sma_5 : count == 6 ? sma_6 : count == 7 ? sma_7 : count == 8 ? sma_8 : count == 9 ? sma_9 : count == 10 ? sma_10 : count == 11 ? sma_11 : count == 12 ? sma_12 : count == 14 ? sma_13 : count == 15 ? sma_14 : count == 16 ? sma_15 : count == 17 ? sma_16 : count == 18 ? sma_17 : count == 19 ? sma_18 : sma_19
var minrangee = 0.0
minrange = minrangpw ? nz(avgprice) * nz(minrangp) : percentw and count <= 1 ? avgprice * .0001 : percentw ? nz(minrangee[1]) : minrangpw == false and percentw == false and truerange == false and avspread == false ? minrang : nz(minrangee[1]) // count==2? nz(minrangee[1]):0
shorenbar = false //input(false, title="Show individual bar time")
renkotrend = 0
renkowave = 0
bar1 = 0.0
Rangebartime = 0.0
Rangebartime_ = 0.0
renkoup = 0.0
renkodown = 0.0
rbt = 0.0
r = 0.0
mins = 0.0
bf = true //input(true, title=" recolour a limbo wave once direction confirmed?")
//Rangebartime := r // na(t3) ? bar1 - bar1[1] : bar1 - bar1[1] - t5
Rangebartime := timeframe.isintraday ? time_close / 60000 - time / 60000 : timeframe.isdaily ? time_close / 3600000 - time / 3600000 : timeframe.isdwm ? 1 : na
volumm = wavechoice == 1 or wavechoice == 4 or wavechoice == 5 or wavechoice == 6 or wavechoice == 7 ? volume : wavechoice == 2 ? close - close[1] : wavechoice == 3 ? Rangebartime : na
//volumme = wavechoice == 3 and volumm == 0 ? r : volumm
volumme = wavechoice == 3 and volumm == 0 ? Rangebartime : volumm
linetra = 40 //input(40, title='wave line transparency 100 is transparent, 0 is not')
var hi = 0.0
var lo = 0.0
Diffu = nz(lo[1]) + minrange - (nz(hi[1]) - minrange) ////1
Diff = Diffu > 0 ? Diffu : 0
showconfirmedpivots = false // input(true, title="Show the minimum wave confirmation?")
showallmult = false //input(true, title="Show factors for rez of volume?")
//calcmult= input(false, title="Let script calc multi factor, red 0s means factor changed on last bar?")
showmulti = mul == 0 and calcmult == false ? true : false
//count= nz(count[1]) + 1
//calcmult = automan == true ? true : false
//lookback = lookbac == 0 ? periods : lookbac
var trendd = 0
var trend = 0
//pricehloc:= high
hi := pricehloc >= nz(hi[1]) - minrange + Diff and pricehloc[1] <= nz(lo[1]) + minrange - Diff and pricehloc - nz(lo[1]) >= minrange or nz(trendd[1]) == -1 and nz(hi[1]) - nz(lo[1]) < 2 * minrange and pricehloc[1] <= nz(lo[1]) + minrange and pricehloc[0] >= nz(lo[1]) + minrange ? pricehloc : nz(trendd[0]) == 1 and pricehloc >= nz(hi[1]) - minrange + Diff and pricehloc[1] <= nz(lo[1]) + minrange - Diff and pricehloc[0] >= nz(lo[1]) + minrange ? pricehloc : pricehloc >= nz(hi[1]) - minrange ? math.max(pricehloc[0], nz(hi[1])) : pricehloc >= nz(lo[1]) + minrange and (nz(trend[1]) == -2 or nz(trend[1]) == -1) ? pricehloc : nz(hi[1])
//pricehloc:=low
trenddo = pricehloc >= nz(hi[0]) - minrange ? 2 : pricehloc >= nz(lo[1]) + minrange ? 1 : pricehloc <= nz(lo[1]) + minrange ? -1 : pricehloc <= nz(hi[0]) - minrange ? -2 : na
lo := pricehloc <= nz(lo[1]) + minrange - Diff and pricehloc[1] >= nz(hi[0]) - minrange + Diff and nz(hi[0]) - pricehloc >= minrange or nz(trendd[1]) == 1 and hi[0] - nz(lo[1]) < 2 * minrange and pricehloc[1] > hi[0] - minrange and pricehloc[0] <= hi[0] - minrange ? pricehloc : pricehloc <= nz(lo[1]) + minrange ? math.min(pricehloc[0], nz(lo[1])) : pricehloc <= nz(hi[0]) - minrange and (nz(trenddo[0]) == 2 or nz(trenddo[0]) == 1) ? pricehloc : nz(lo[1])
trend := pricehloc >= nz(hi[0]) - minrange ? 2 : pricehloc >= nz(lo[0]) + minrange ? 1 : pricehloc <= nz(lo[0]) + minrange ? -1 : pricehloc <= nz(hi[0]) - minrange ? -2 : na
trendd := hi[0] != hi[1] or hi[0] == pricehloc and nz(trendd[1]) == -1 ? 1 : lo[0] != lo[1] or lo[0] == pricehloc and nz(trendd[1]) == 1 ? -1 : nz(trendd[1]) == 1 and not(lo[0] > lo[1] or lo[0] == pricehloc and nz(trendd[1]) == 1) ? 1 : nz(trendd[1]) == -1 and not(hi[0] < hi[1] or hi[0] == pricehloc and nz(trendd[1]) == -1) ? -1 : 0
ct = nz(trendd[0]) == 1 and nz(trendd[1]) == -1 ? 1 : nz(trendd[0]) == -1 and nz(trendd[1]) == -1 ? -2 : nz(trendd[0]) == 1 and nz(trendd[1]) == 1 ? 2 : nz(trendd[0]) == -1 and nz(trendd[1]) == 1 ? -1 : na
maxpivot = trendd == 1 and nz(hi[0]) == pricehloc ? pricehloc : na
mphigh = maxpivot ? high : na
minpivot = trendd == -1 and nz(lo[0]) == pricehloc ? pricehloc : na
maxpivottf = maxpivot == pricehloc ? true : false
minpivottf = minpivot == pricehloc ? true : false
var limboup = 0
var lvolup = 0.0
var limbodown = 0
var lvoldown = 0.0
limboup := pricehloc < nz(hi[0]) and nz(trendd[0]) == 1 ? nz(limboup[1]) + 1 : nz(trendd[0]) == 1 and nz(trendd[1]) == -1 ? nz(limboup[1]) : 0
lvolup := nz(limboup[0]) == 0 ? 0 : nz(limboup[0]) >= 1 ? nz(lvolup[1]) + volumme : volumme
limbodown := pricehloc > nz(lo[0]) and nz(trendd[0]) == -1 ? nz(limbodown[1]) + 1 : nz(trendd[0]) == -1 and nz(trendd[1]) == 1 ? nz(limbodown[1]) : 0
lvoldown := nz(limbodown[0]) == 0 ? 0 : nz(limbodown[0]) >= 1 ? nz(lvoldown[1]) + volumme : volumme
// use limbo up cont to calc volume
var Counttrendup = 0
var Counttrenddown = 0
var volup = 0.0
var voldown = 0.0
Counttrendup := nz(trendd[0]) == 1 and nz(trendd[1]) == -1 ? 1 + nz(limbodown[1]) : nz(trendd[0]) == -1 and nz(trendd[1]) == 1 ? na : nz(trendd[0]) == 1 and nz(trendd[1]) == 1 ? nz(Counttrendup[1]) + 1 : 0
Counttrenddown := nz(trendd[0]) == -1 and nz(trendd[1]) == 1 ? 1 + nz(limboup[1]) : nz(trendd[0]) == 1 and nz(trendd[1]) == -1 ? na : nz(trendd[0]) == -1 and nz(trendd[1]) == -1 ? nz(Counttrenddown[1]) + 1 : 0
// direction = nz(Counttrendup[0]) >= 1 and nz(limboup[0]) == 0 ? 2 :
// nz(Counttrenddown[0]) >= 1 and nz(limbodown[0]) == 0 ? -2 :
// nz(Counttrendup[0]) >= 1 and nz(limboup[0]) > 0 ? 1 :
// nz(Counttrenddown[0]) >= 1 and nz(limbodown[0]) > 0 ? -1 : na
volup := nz(limbodown[0]) == 0 and nz(Counttrendup[0]) == 0 ? 0 : nz(limbodown[0]) >= 1 and nz(Counttrendup[0]) == 0 ? nz(volup[1]) + volumme : nz(limbodown[1]) >= 1 and nz(Counttrendup[0]) >= 1 and nz(trendd[0]) == 1 and nz(trendd[1]) == -1 ? nz(volup[1]) + volumme : nz(limbodown[1]) == 0 and nz(Counttrendup[0]) >= 1 and nz(trendd[0]) == 1 and nz(trendd[1]) == -1 ? volumme : nz(limbodown[1]) == 0 and nz(Counttrendup[0]) >= 1 and nz(trendd[0]) == 1 and nz(trendd[1]) == 1 ? nz(volup[1]) + volumme : na
voldown := nz(limboup[0]) == 0 and nz(Counttrenddown[0]) == 0 ? 0 : nz(limboup[0]) >= 1 and nz(Counttrenddown[0]) == 0 ? nz(voldown[1]) + volumme : nz(limboup[1]) >= 1 and nz(Counttrenddown[0]) >= 1 and nz(trendd[0]) == -1 and nz(trendd[1]) == 1 ? nz(voldown[1]) + volumme : nz(limboup[1]) == 0 and nz(Counttrenddown[0]) >= 1 and nz(trendd[0]) == -1 and nz(trendd[1]) == 1 ? volumme : nz(limboup[1]) == 0 and nz(Counttrenddown[0]) >= 1 and nz(trendd[0]) == -1 and nz(trendd[1]) == -1 ? nz(voldown[1]) + volumme : na
// ct==1 change to up, ct== 2 stay up, ct= =-1 change to down, ct== 2 stay down
toppe = limboup[1] == 0 and ct == -1 ? maxpivot[1] : limboup[1] == 1 and ct == -1 ? maxpivot[2] : limboup[1] == 2 and ct == -1 ? maxpivot[3] : limboup[1] == 3 and ct == -1 ? maxpivot[4] : limboup[1] == 4 and ct == -1 ? maxpivot[5] : limboup[1] == 5 and ct == -1 ? maxpivot[6] : limboup[1] == 6 and ct == -1 ? maxpivot[7] : limboup[1] == 7 and ct == -1 ? maxpivot[8] : limboup[1] == 8 and ct == -1 ? maxpivot[9] : limboup[1] == 9 and ct == -1 ? maxpivot[10] : limboup[1] == 10 and ct == -1 ? maxpivot[11] : limboup[1] == 11 and ct == -1 ? maxpivot[12] : limboup[1] == 12 and ct == -1 ? maxpivot[13] : limboup[1] == 13 and ct == -1 ? maxpivot[14] : limboup[1] == 14 and ct == -1 ? maxpivot[15] : limboup[1] == 15 and ct == -1 ? maxpivot[16] : limboup[1] == 16 and ct == -1 ? maxpivot[17] : limboup[1] == 17 and ct == -1 ? maxpivot[18] : limboup[1] == 18 and ct == -1 ? maxpivot[19] : limboup[1] == 19 and ct == -1 ? maxpivot[20] : limboup[1] == 20 and ct == -1 ? maxpivot[21] : limboup[1] == 21 and ct == -1 ? maxpivot[22] : limboup[1] == 22 and ct == -1 ? maxpivot[23] : limboup[1] == 23 and ct == -1 ? maxpivot[24] : limboup[1] == 24 and ct == -1 ? maxpivot[25] : limboup[1] == 25 and ct == -1 ? maxpivot[26] : limboup[1] == 26 and ct == -1 ? maxpivot[27] : limboup[1] == 27 and ct == -1 ? maxpivot[28] : limboup[1] == 28 and ct == -1 ? maxpivot[29] : limboup[1] == 29 and ct == -1 ? maxpivot[30] : limboup[1] == 30 and ct == -1 ? maxpivot[31] : limboup[1] == 31 and ct == -1 ? maxpivot[32] : limboup[1] == 32 and ct == -1 ? maxpivot[33] : limboup[1] == 33 and ct == -1 ? maxpivot[34] : limboup[1] == 34 and ct == -1 ? maxpivot[35] : limboup[1] == 35 and ct == -1 ? maxpivot[36] : limboup[1] == 36 and ct == -1 ? maxpivot[37] : limboup[1] == 37 and ct == -1 ? maxpivot[38] : limboup[1] == 38 and ct == -1 ? maxpivot[39] : limboup[1] == 39 and ct == -1 ? maxpivot[40] : limboup[1] == 40 and ct == -1 ? maxpivot[41] : limboup[1] == 41 and ct == -1 ? maxpivot[42] : limboup[1] == 42 and ct == -1 ? maxpivot[43] : limboup[1] == 43 and ct == -1 ? maxpivot[44] : limboup[1] == 44 and ct == -1 ? maxpivot[45] : limboup[1] == 45 and ct == -1 ? maxpivot[46] : limboup[1] == 46 and ct == -1 ? maxpivot[47] : limboup[1] == 47 and ct == -1 ? maxpivot[48] : limboup[1] == 48 and ct == -1 ? maxpivot[49] : limboup[1] == 49 and ct == -1 ? maxpivot[40] : limboup[1] == 50 and ct == -1 ? maxpivot[51] : limboup[1] == 51 and ct == -1 ? maxpivot[52] : limboup[1] == 52 and ct == -1 ? maxpivot[53] : limboup[1] == 53 and ct == -1 ? maxpivot[54] : limboup[1] == 54 and ct == -1 ? maxpivot[55] : limboup[1] == 55 and ct == -1 ? maxpivot[56] : limboup[1] == 56 and ct == -1 ? maxpivot[57] : limboup[1] == 57 and ct == -1 ? maxpivot[58] : limboup[1] == 58 and ct == -1 ? maxpivot[59] : limboup[1] == 59 and ct == -1 ? maxpivot[60] : limboup[1] == 60 and ct == -1 ? maxpivot[61] : limboup[1] == 61 and ct == -1 ? maxpivot[62] : limboup[1] == 62 and ct == -1 ? maxpivot[63] : limboup[1] == 63 and ct == -1 ? maxpivot[64] : limboup[1] == 64 and ct == -1 ? maxpivot[65] : limboup[1] == 65 and ct == -1 ? maxpivot[66] : limboup[1] == 66 and ct == -1 ? maxpivot[67] : limboup[1] == 67 and ct == -1 ? maxpivot[68] : limboup[1] == 68 and ct == -1 ? maxpivot[69] : limboup[1] == 69 and ct == -1 ? maxpivot[70] : limboup[1] == 70 and ct == -1 ? maxpivot[71] : limboup[1] == 71 and ct == -1 ? maxpivot[72] : na
bottomme = limbodown[1] == 0 and ct == 1 ? minpivot[1] : limbodown[1] == 1 and ct == 1 ? minpivot[2] : limbodown[1] == 2 and ct == 1 ? minpivot[3] : limbodown[1] == 3 and ct == 1 ? minpivot[4] : limbodown[1] == 4 and ct == 1 ? minpivot[5] : limbodown[1] == 5 and ct == 1 ? minpivot[6] : limbodown[1] == 6 and ct == 1 ? minpivot[7] : limbodown[1] == 7 and ct == 1 ? minpivot[8] : limbodown[1] == 8 and ct == 1 ? minpivot[9] : limbodown[1] == 9 and ct == 1 ? minpivot[10] : limbodown[1] == 10 and ct == 1 ? minpivot[11] : limbodown[1] == 11 and ct == 1 ? minpivot[12] : limbodown[1] == 12 and ct == 1 ? minpivot[13] : limbodown[1] == 13 and ct == 1 ? minpivot[14] : limbodown[1] == 14 and ct == 1 ? minpivot[15] : limbodown[1] == 15 and ct == 1 ? minpivot[16] : limbodown[1] == 16 and ct == 1 ? minpivot[17] : limbodown[1] == 17 and ct == 1 ? minpivot[18] : limbodown[1] == 18 and ct == 1 ? minpivot[19] : limbodown[1] == 19 and ct == 1 ? minpivot[20] : limbodown[1] == 20 and ct == 1 ? minpivot[21] : limbodown[1] == 21 and ct == 1 ? minpivot[22] : limbodown[1] == 22 and ct == 1 ? minpivot[23] : limbodown[1] == 23 and ct == 1 ? minpivot[24] : limbodown[1] == 24 and ct == 1 ? minpivot[25] : limbodown[1] == 25 and ct == 1 ? minpivot[26] : limbodown[1] == 26 and ct == 1 ? minpivot[27] : limbodown[1] == 27 and ct == 1 ? minpivot[28] : limbodown[1] == 28 and ct == 1 ? minpivot[29] : limbodown[1] == 29 and ct == 1 ? minpivot[30] : limbodown[1] == 30 and ct == 1 ? minpivot[31] : limbodown[1] == 31 and ct == 1 ? minpivot[32] : limbodown[1] == 32 and ct == 1 ? minpivot[33] : limbodown[1] == 33 and ct == 1 ? minpivot[34] : limbodown[1] == 34 and ct == 1 ? minpivot[35] : limbodown[1] == 35 and ct == 1 ? minpivot[36] : limbodown[1] == 36 and ct == 1 ? minpivot[37] : limbodown[1] == 37 and ct == 1 ? minpivot[38] : limbodown[1] == 38 and ct == 1 ? minpivot[39] : limbodown[1] == 39 and ct == 1 ? minpivot[40] : limbodown[1] == 40 and ct == 1 ? minpivot[41] : limbodown[1] == 41 and ct == 1 ? minpivot[42] : limbodown[1] == 42 and ct == 1 ? minpivot[43] : limbodown[1] == 43 and ct == 1 ? minpivot[44] : limbodown[1] == 44 and ct == 1 ? minpivot[45] : limbodown[1] == 45 and ct == 1 ? minpivot[46] : limbodown[1] == 46 and ct == 1 ? minpivot[47] : limbodown[1] == 47 and ct == 1 ? minpivot[48] : limbodown[1] == 48 and ct == 1 ? minpivot[49] : limbodown[1] == 49 and ct == 1 ? minpivot[50] : limbodown[1] == 50 and ct == 1 ? minpivot[51] : limbodown[1] == 51 and ct == 1 ? minpivot[52] : limbodown[1] == 52 and ct == 1 ? minpivot[53] : limbodown[1] == 53 and ct == 1 ? minpivot[54] : limbodown[1] == 54 and ct == 1 ? minpivot[55] : limbodown[1] == 55 and ct == 1 ? minpivot[56] : limbodown[1] == 56 and ct == 1 ? minpivot[57] : limbodown[1] == 57 and ct == 1 ? minpivot[58] : limbodown[1] == 58 and ct == 1 ? minpivot[59] : limbodown[1] == 59 and ct == 1 ? minpivot[60] : limbodown[1] == 60 and ct == 1 ? minpivot[61] : limbodown[1] == 61 and ct == 1 ? minpivot[62] : limbodown[1] == 62 and ct == 1 ? minpivot[63] : limbodown[1] == 63 and ct == 1 ? minpivot[64] : limbodown[1] == 64 and ct == 1 ? minpivot[65] : limbodown[1] == 65 and ct == 1 ? minpivot[66] : limbodown[1] == 66 and ct == 1 ? minpivot[67] : limbodown[1] == 67 and ct == 1 ? minpivot[68] : limbodown[1] == 68 and ct == 1 ? minpivot[69] : limbodown[1] == 69 and ct == 1 ? minpivot[70] : limbodown[1] == 70 and ct == 1 ? minpivot[71] : limbodown[1] == 71 and ct == 1 ? minpivot[72] : na
// time estimate bars
var deltaclose = 0.0
begin = toppe > 0 ? Counttrendup[1] + 1 : bottomme > 0 ? Counttrenddown[1] + 1 : na
end = toppe > 0 ? limboup[1] + 1 : bottomme > 0 ? limbodown[1] + 1 : na
time_ = (begin - end) * r //new algo does not use this uses time_close instead
bars_ = begin - end // use for ord type avg wave volume/bar
// startclose=close[begin]
// endclose=close[end]
deltaclose := toppe or bottomme ? math.abs(close[begin] - close[end]) : na
//plot(deltaclose,style=cross, color=orange, linewidth=4 )
alertcondition(toppe, title='a top confirmed', message='Weis wave top confirmed!')
alertcondition(bottomme, title='a bottom confirmed', message='Weis wave bottom confirmed!')
plotvolup1 = ct == -1 ? volup[1] - lvolup[1] : na //maxpivottf==true and
//plotvolup = wavechoice == 5 ?plotvolup1 / bars_: wavechoice == 4 ? deltaclose/plotvolup1 : plotvolup1
plotvolup = wavechoice == 5 ? plotvolup1 / bars_ : wavechoice == 4 ? plotvolup1 / deltaclose : plotvolup1 // speed index style could mult x 1.53
//plotvolup = wavechoice == 5 ?plotvolup1 / bars_: wavechoice == 4 ? plotvolup1 / (plottoppeclose - plotbottommeclose) : plotvolup1
// should replace with log10 truncated with out decimal round(log10(plotvolup))-log10(plotvolup) truncate to whole number without rounding up
//old way #13 now 44 or 43 Weis V4 jayy
cpvabs = math.round(math.log10(plotvolup) - .5)
cpv = cpvabs >= 19 and wavechoice == 3 ? 1 : cpvabs
var cpvtoppe = 0
var cpvdbottomme = 0
cpvtoppe := toppe ? cpv : nz(cpvtoppe[1])
plotvoldown1 = ct == 1 ? math.abs(voldown[1] - lvoldown[1]) : na //maxpivottf==true and
//(bottomme?plotvoldown/-(plottoppeclose-plotbottommeclose):toppe?plotvolup/(plottoppeclose-plotbottommeclose)
//plotvoldown = wavechoice == 5 ?abs(plotvoldown1) / bars_: wavechoice == 4 ? deltaclose/abs(plotvoldown1): abs(plotvoldown1)
plotvoldown = wavechoice == 5 ? math.abs(plotvoldown1) / bars_ : wavechoice == 4 ? math.abs(plotvoldown1) / deltaclose : math.abs(plotvoldown1) // speed index style
//plotvoldown = wavechoice == 5 ?abs(plotvoldown1) / bars_: wavechoice == 4 ? abs(plotvoldown1) / (plottoppeclose - plotbottommeclose) :
// abs(plotvoldown1)
// cpvdabs= log10(plotvoldown)>0 and round(log10(plotvoldown))-log10(plotvoldown)>0?round(log10(plotvoldown))-1:
// log10(plotvoldown)<0 and round(log10(plotvoldown))-log10(plotvoldown)<0?round(log10(plotvoldown)):round(log10(plotvoldown))
cpvdabs = math.round(math.log10(plotvoldown) - .5) //round(log10(plotvoldown))-log10(plotvoldown)>0?round(log10(plotvoldown))-1:round(log10(plotvoldown))
cpvd = cpvdabs == 19 and wavechoice == 3 ? 1 : cpvdabs
k = cpvd > 20 or cpv > 20 ? true : false
cpvdbottomme := bottomme ? cpvd : nz(cpvdbottomme[1])
var cpvhe = 0.0
highest_1 = ta.highest(cpvtoppe, 50)
highest_2 = ta.highest(cpvdbottomme, 50)
highest_3 = ta.highest(cpvtoppe, 50)
highest_4 = ta.highest(cpvdbottomme, 50)
highest_5 = ta.highest(cpvtoppe, 250)
highest_6 = ta.highest(cpvdbottomme, 250)
highest_7 = ta.highest(cpvtoppe, 250)
highest_8 = ta.highest(cpvdbottomme, 250)
highest_9 = ta.highest(cpvtoppe, 500)
highest_10 = ta.highest(cpvdbottomme, 500)
highest_11 = ta.highest(cpvtoppe, 500)
highest_12 = ta.highest(cpvdbottomme, 500)
highest_13 = ta.highest(cpvtoppe, 10)
highest_14 = ta.highest(cpvdbottomme, 10)
highest_15 = ta.highest(cpvtoppe, 10)
highest_16 = ta.highest(cpvdbottomme, 10)
highest_17 = ta.highest(cpvtoppe, 30)
highest_18 = ta.highest(cpvdbottomme, 30)
highest_19 = ta.highest(cpvtoppe, 30)
highest_20 = ta.highest(cpvdbottomme, 30)
highest_21 = ta.highest(cpvtoppe, 50)
highest_22 = ta.highest(cpvdbottomme, 50)
highest_23 = ta.highest(cpvtoppe, 50)
highest_24 = ta.highest(cpvdbottomme, 50)
highest_25 = ta.highest(cpvtoppe, 100)
highest_26 = ta.highest(cpvdbottomme, 100)
highest_27 = ta.highest(cpvtoppe, 100)
highest_28 = ta.highest(cpvdbottomme, 100)
highest_29 = ta.highest(cpvtoppe, 200)
highest_30 = ta.highest(cpvdbottomme, 200)
highest_31 = ta.highest(cpvtoppe, 200)
highest_32 = ta.highest(cpvdbottomme, 200)
highest_33 = ta.highest(cpvtoppe, 500)
highest_34 = ta.highest(cpvdbottomme, 500)
highest_35 = ta.highest(cpvtoppe, 500)
highest_36 = ta.highest(cpvdbottomme, 500)
highest_37 = ta.highest(cpvtoppe, 1000)
highest_38 = ta.highest(cpvdbottomme, 1000)
highest_39 = ta.highest(cpvtoppe, 1000)
highest_40 = ta.highest(cpvdbottomme, 1000)
highest_41 = ta.highest(cpvtoppe, 4000)
highest_42 = ta.highest(cpvdbottomme, 4000)
highest_43 = ta.highest(cpvtoppe, 4000)
highest_44 = ta.highest(cpvdbottomme, 4000)
cpvhe := calcmult_a == 1 and count > 50 ? nz(highest_1) > nz(highest_2) ? nz(highest_3) : nz(highest_4) : calcmult_a == 2 and count > 250 ? nz(highest_5) > nz(highest_6) ? nz(highest_7) : nz(highest_8) : calcmult_a == 3 and count > 500 ? nz(highest_9) > nz(highest_10) ? nz(highest_11) : nz(highest_12) : count >= 10 and count < 30 ? nz(highest_13) > nz(highest_14) ? nz(highest_15) : nz(highest_16) : count >= 30 and count < 50 ? nz(highest_17) > nz(highest_18) ? nz(highest_19) : nz(highest_20) : count >= 50 and count < 100 ? nz(highest_21) > nz(highest_22) ? nz(highest_23) : nz(highest_24) : count >= 100 and count < 200 ? nz(highest_25) > nz(highest_26) ? nz(highest_27) : nz(highest_28) : count >= 200 and count < 500 and (timeframe.period == '1' or timeframe.period == '2' or timeframe.period == '3' or timeframe.period == '4' or timeframe.period == '5') ? nz(highest_29) > nz(highest_30) ? nz(highest_31) : nz(highest_32) : count >= 500 and count < 1000 and (timeframe.period == '1' or timeframe.period == '2' or timeframe.period == '3' or timeframe.period == '4' or timeframe.period == '5') ? nz(highest_33) > nz(highest_34) ? nz(highest_35) : nz(highest_36) : count >= 1000 and count < 4000 and (timeframe.period == '1' or timeframe.period == '2' or timeframe.period == '3' or timeframe.period == '4' or timeframe.period == '5') ? nz(highest_37) > nz(highest_38) ? nz(highest_39) : nz(highest_40) : count >= 4000 and (timeframe.period == '1' or timeframe.period == '2' or timeframe.period == '3' or timeframe.period == '4' or timeframe.period == '5') ? nz(highest_41) > nz(highest_42) ? nz(highest_43) : nz(highest_44) : count >= 200 ? nz(highest_29) > nz(highest_30) ? nz(highest_31) : nz(highest_32) : na
aa = cpvtoppe //aa=cpvtoppe, bb=cpvdbottomme //aa=lowest(cpvtoppe, 2000), bb=lowest(cpvdbottomme, 2000)
bb = cpvdbottomme
var famult = 0.0
ab = 0.0
ba = 0.0
abh = 0.0
bal = 0.0
ab := nz(aa[0]) >= 1 and nz(aa[1]) < 1 ? nz(aa[0]) : aa[0] < nz(ab[1]) ? nz(aa[0]) : aa[0] > nz(aa[1]) ? nz(ab[1]) : aa[0] == nz(aa[1]) ? nz(ab[1]) : nz(ab[1]) //aa[0]>=nz(aa[1])?nz(aa[1]):aa[0]==0?nz(ab[1]):9 //lowest(cpvtoppe, 2000), bb=lowest(cpvdbottomme, 2000)
abh := aa[0] > nz(abh[1]) ? nz(aa[0]) : aa[0] < nz(aa[1]) ? nz(abh[1]) : aa[0] == nz(aa[1]) ? nz(abh[1]) : nz(abh[1])
//nz(aa[0])>=1 and nz(aa[1])<1? nz(aa[0]):
ba := nz(bb[0]) >= 1 and nz(bb[1]) < 1 ? nz(bb[0]) : bb[0] < nz(ba[1]) ? nz(bb[0]) : bb[0] > nz(bb[1]) ? nz(ba[1]) : bb[0] == nz(bb[1]) ? nz(ba[1]) : nz(ba[1])
bal := bb[0] > nz(bal[1]) ? nz(bb[0]) : bb[0] < nz(bb[1]) ? nz(bal[1]) : bb[0] == nz(bb[1]) ? nz(bal[1]) : nz(bal[1])
//nz(bb[0])>=1 and nz(bb[1])<1? nz(bb[0]):
famult := abh < 50 or bal < 50 ? math.max(abh, bal) : cpvhe
//calcmult and
// multi = calcmult_a==6?pow(10,famult-2): calcmult_a==7?pow(10,famult-3):calcmult ? pow(10, cpvh - 2) :
// pow(10, (wavechoice == 1 or wavechoice == 4 or wavechoice==5 or wavechoice==6 or wavechoice==7? mult : (wavechoice==2 or wavechoice == 3) and cpvh>=0 ? mult -2 : mult) - 2)
calcmultm = calcmult and calcmult_a == 6 ? true : false
calcmult_m = calcmultm or calcmult ? true : false
cpvh = 0.0
cpvh := calcmultm ? famult : cpvhe //(timeframe.isdaily or timeframe.period == "4H") and cpvhe == -10 and
multsen = calcmult_m and shovol_ == 'Automatic X 10' ? 1 : calcmult_m and shovol_ == 'Automatic X 100' ? 0 : calcmult_m and shovol_ == 'Automatic X 0.1' ? 3 : calcmult_m and shovol_ == 'Automatic X 0.01' ? 4 : calcmult ? 2 : 4
multi = calcmult_m ? math.pow(10, cpvh - multsen) : math.pow(10, (wavechoice == 1 or wavechoice == 4 or wavechoice == 5 or wavechoice == 6 or wavechoice == 7 ? mult : (wavechoice == 2 or wavechoice == 3) and cpvh >= 0 ? mult - 2 : mult) - 2)
cpvh_new = calcmultm ? famult + 2 - multsen : calcmult ? cpvh + 2 - multsen : na
var cpvhm = 0.0
cpvhm := calcmult and calcmult_a == 6 ? famult - 2 : calcmult_a == 7 ? famult - 3 : calcmult ? cpvh - 2 : wavechoice == 1 or wavechoice == 4 or wavechoice == 5 or wavechoice == 6 or wavechoice == 7 ? cpvh - 2 : wavechoice == 3 ? cpvh : cpvh
var cpvmult = 0.0
cpvmult := math.max(aa, bb)
// multi = calcmult ? pow(10, cpvh - 2) :
// pow(10, (wavechoice == 1 or wavechoice == 4 or wavechoice==5 or wavechoice==6 or wavechoice==7? mult : wavechoice == 3 ? mult - 10 : mult - 10) - 2)
change = multi != nz(multi[1]) ? true : false
arreg = plotvolup / multi
ar = calcmult_m ? arreg >= 1000 ? arreg / 10 : arreg : showmulti and wavechoice == 2 and cpvh >= 0 ? cpv + 2 : (wavechoice == 1 or wavechoice == 4 or wavechoice == 5 or wavechoice == 6 or wavechoice == 7) and showmulti ? cpv : (wavechoice == 2 or wavechoice == 3) and showmulti and cpvh >= 0 ? cpv + 2 : showmulti and (wavechoice == 2 or wavechoice == 3) and cpvh < 0 ? cpv + 1 : arreg >= 1000 ? arreg / 10 : arreg // arreg //(arreg<1?arreg*10:arreg>=1000?arreg/10:arreg)
var armult = 0.0
armult := nz(ar[0]) > 0 ? nz(ar[0]) : nz(armult[1]) != nz(ar[0]) and nz(ar[0]) > 0 and nz(armult[1]) > 0 ? nz(ar[0]) : nz(armult[1])
y = ar < 1 ? 0 : na
A3i = math.round((math.round(ar) - 5) / 10) * 10
A3 = math.round(ar) - A3i
A2i = math.round((A3i / 10 - 5) / 10) * 10
A2 = A3i / 10 < 10 ? A3i / 10 : ar < 10 ? 0 : A3i / 10 - A2i
A1i = math.round((A2i / 10 - 5) / 10) * 10
A1 = A2i / 10 < 10 ? A2i / 10 : A3i < 10 ? 0 : A2i / 10 - A1i
T = A1i / 10 > 0 and A1i / 10 < 10 ? A1i / 10 : na
ardreg = plotvoldown / multi
ard = calcmult_m ? ardreg >= 1000 ? ardreg / 10 : ardreg : showmulti and wavechoice == 2 and cpvh >= 0 ? cpvd + 2 : (wavechoice == 1 or wavechoice == 4 or wavechoice == 5 or wavechoice == 6 or wavechoice == 7) and showmulti ? cpvd : (wavechoice == 2 or wavechoice == 3) and showmulti and cpvh >= 0 ? cpvd + 2 : showmulti and (wavechoice == 2 or wavechoice == 3) and cpvh < 0 ? cpvd + 1 : ardreg >= 1000 ? ardreg / 10 : ardreg
yd = ard < 1 ? 0 : na
A3id = math.round((math.round(ard) - 5) / 10) * 10
A3D = math.round(ard) - A3id
A2id = math.round((A3id / 10 - 5) / 10) * 10
A2D = A3id / 10 < 10 ? A3id / 10 : ard < 10 ? 0 : A3id / 10 - A2id
A1id = math.round((A2id / 10 - 5) / 10) * 10
A1D = A2id / 10 < 10 ? A2id / 10 : A3id < 10 ? 0 : A2id / 10 - A1id
Td = A1id / 10 > 0 and A1id / 10 < 10 ? A1id / 10 : na
topp = 0.0
bottomm = 0.0
multtoppelast = 0.0
multbottommelast = 0.0
interimtop = 0.0
interimbottom = 0.0
topp := toppe > 0 ? nz(toppe) : nz(topp[1])
bottomm := bottomme > 0 ? nz(bottomme) : nz(bottomm[1])
multtoppelast := toppe ? multi : nz(multtoppelast[1])
multbottommelast := bottomme ? multi : nz(multbottommelast[1])
interimtop := maxpivottf ? maxpivot : nz(interimtop[1])
interimbottom := minpivottf ? minpivot : nz(interimbottom[1])
minrangee := minrangpw == true ? avgprice * minrangp : truerange ? trange : avspread ? minrangetr : percentw and nz(ct) == 2 ? (nz(interimtop) - nz(bottomm[0])) * (percent / 100) : percentw and nz(ct) == 1 ? (nz(interimtop) - nz(bottomm[0])) * (percent / 100) : percentw and nz(ct) == -2 ? (nz(topp[0]) - nz(interimbottom)) * (percent / 100) : percentw and nz(ct) == -1 ? (nz(topp[0]) - nz(interimbottom)) * (percent / 100) : minrangpw == false and percentw == false and truerange == false and avspread == false ? minrang : na //nz(ct)==1 or
lbwvv = false
plot(oldwave ? not lbwvv ? ct == -1 and showweiswave ? toppe : ct == 1 and showweiswave ? bottomme : maxpivottf == true and not showweiswave ? maxpivot : minpivottf == true and not showweiswave ? minpivot : na : maxpivottf == true ? maxpivot : minpivottf == true ? minpivot : na : na, color=not lbwvv ? showweiswave ? ct == -1 ? color.green : ct == 1 ? color.red : na : maxpivottf == true ? color.green : color.red : maxpivottf == true ? color.green : color.red, offset=not lbwvv ? showweiswave ? -1 : 0 : -1, linewidth=3)
pivote = maxpivottf == true ? maxpivot : minpivottf == true ? minpivot : na
txtsize = ts == 'tiny' ? size.tiny : ts == 'small' ? size.small : ts == 'normal' ? size.normal : ts == 'large' ? size.large : ts == 'huge' ? size.huge : ts == 'auto' ? size.auto : size.auto
line weisline = na
need_manual_calc = false
shocalc = false
shocalc := shovol_ == 'Weis truncated volume' or shovol_ == 'Automatic X 10' or shovol_ == 'Automatic X 100' or shovol_ == 'Automatic X 0.1' or shovol_ == 'Automatic X 0.01' ? true : false
shotruvol = shovol_ == 'Show true wave volume' ? true : shocalc ? false : na
need_manual_calc := shotruvol ? false : arreg <= .1 and (mult > 0 or mult < 0) or ardreg < .1 and (mult > 0 or mult < 0) or arreg >= 10000 and (mult > 0 or mult < 0) or ardreg >= 10000 and (mult > 0 or mult < 0) or k or limboup > 40 or limbodown > 40 or toppe and multbottommelast != multi or bottomme and multtoppelast != multi ? true : false
//need_manual_calc:=shovol_=="Show full true wave volume"?false:need_manual_calc[1]
art = 0.0
ardt = 0.0
art := shovol_ == 'Show true wave volume' ? plotvolup : shocalc ? ar : na
ardt := shovol_ == 'Show true wave volume' ? plotvoldown : shocalc ? ard : na
var cpvh_ = string(na)
//shovol_== "Automatic X 10" or shovol_== "Automatic X 100"
cpvh_ := shovol_ != 'Show true wave volume' ? cpvh == 4 ? '#' : cpvh == 3 ? '#' : cpvh == 2 ? '#' : cpvh == 1 ? '#.#' : cpvh == 0 ? '#.###' : cpvh == -1 ? '#.####' : cpvh == -2 ? '#.#####' : na : na //'#.#######' //
// limitcph_ to 3 digits? cpvh_:= shovol_!= "Show true wave volume"?(cpvh==3?'#':cpvh==2?'#':cpvh==1?'#.#':cpvh==0?'#.##':cpvh==-1?'#.###':na):na //'#.#######' //pace
artbar = art / bars_
ardtbar = ardt / bars_
arbar = ar / bars_
ardbar = ard / bars_
artsigdig = artbar >= 100 ? '#' : artbar >= 10 ? '#.#' : artbar >= 1 ? '#.##' : artbar >= .1 ? '#.###' : artbar >= .01 ? '#.####' : na
ardtsigdig = ardtbar >= 100 ? '#' : ardtbar >= 10 ? '#.#' : ardtbar >= 1 ? '#.##' : ardtbar >= .1 ? '#.###' : ardtbar >= .01 ? '#.####' : na
// if vol over ord vol has too few digits employ this
arsigdig = arbar >= 100 ? '#' : arbar >= 10 ? '#.#' : arbar >= 1 ? '#.##' : arbar >= .1 ? '#.###' : arbar >= .01 ? '#.####' : na
ardsigdig = ardbar >= 100 ? '#' : ardbar >= 10 ? '#.#' : ardbar >= 1 ? '#.##' : ardbar >= .1 ? '#.###' : ardbar >= .01 ? '#.####' : na
upsigdig = plotvolup >= 100 ? '#' : plotvolup >= 10 ? '#.#' : plotvolup >= 1 ? '#.##' : plotvolup >= .1 ? '#.###' : plotvolup >= .01 ? '#.####' : plotvolup >= .001 ? '#.#####' : plotvolup >= .0001 ? '#.######' : plotvolup >= .00001 ? '#.#######' : plotvolup >= .000001 ? '#.########' : plotvolup >= .0000001 ? '#.########' : plotvolup >= .00000001 ? '#.##########' : plotvolup >= .000000001 ? '#.###########' : plotvolup >= .0000000001 ? '#.############' : plotvolup >= .00000000001 ? '#.#############' : plotvolup >= .000000000001 ? '#.##############' : na
downsigdig = plotvoldown >= 100 ? '#' : plotvoldown >= 10 ? '#.#' : plotvoldown >= 1 ? '#.##' : plotvoldown >= .1 ? '#.###' : plotvoldown >= .01 ? '#.####' : plotvoldown >= .001 ? '#.#####' : plotvoldown >= .0001 ? '#.######' : plotvoldown >= .00001 ? '#.#######' : plotvoldown >= .000001 ? '#.########' : plotvoldown >= .0000001 ? '#.########' : plotvoldown >= .00000001 ? '#.##########' : plotvoldown >= .000000001 ? '#.###########' : plotvoldown >= .0000000001 ? '#.############' : plotvoldown >= .00000000001 ? '#.#############' : plotvoldown >= .000000000001 ? '#.##############' : na
//210
nspace = string(na)
nspace := rf == 0 ? na : rf == 1 ? '\n' : rf == 2 ? '\n\n' : rf == 3 ? '\n\n\n' : rf == 4 ? '\n\n\n\n' : rf == 5 ? '\n\n\n\n\n' : rf == 6 ? '\n\n\n\n\n\n' : rf == 7 ? '\n\n\n\n\n\n\n' : rf == 8 ? '\n\n\n\n\n\n\n\n' : na
//replace in both below textcolor=need_manual_calc and shovol_!= "Show true wave volume"?colorr:(wavechoice== 2 or wavechoice==3)?colorc:colorb
dnlbl = KO ? bottomme and shovol ? label.new(bar_index[limbodown[1] + 1], bottomme - 1, style=label.style_none, yloc=yloc.belowbar, textcolor=need_manual_calc and shovol_ != 'Show true wave volume' ? colorr : wavechoice == 2 or wavechoice == 3 ? colorc : colorb, size=txtsize, text=shotruvol == false ? (wavechoice == 2 or wavechoice == 3) and calcmult_m and cpvh >= -1 and cpvh <= 3 ? nspace + str.tostring(plotvoldown, cpvh_) : ardreg < .1 and (mult > 0 or mult < 0) ? nspace + 'down' : ardreg > 9999 and (mult > 0 or mult < 0) ? nspace + 'up' : wavechoice != 6 and wavechoice != 7 ? ardreg > 999 and ardreg <= 9999 ? nspace + str.tostring(math.round(ard * 10)) : nspace + str.tostring(math.round(ard)) : wavechoice == 6 ? ardreg > 999 and ardreg <= 9999 ? nspace + str.tostring(math.round(ard * 10)) + '\n' + str.tostring(10 * bars_) : nspace + str.tostring(math.round(ard)) + '\n' + str.tostring(bars_) : ardreg > 999 and ardreg <= 9999 ? nspace + str.tostring(math.round(ard * 10)) + '\n' + str.tostring(math.round(10 * ard / bars_)) : nspace + str.tostring(math.round(ard)) + '\n' + str.tostring(math.round(ard / bars_)) : wavechoice != 6 and wavechoice != 7 ? ardreg > 999 and ardreg <= 9999 ? nspace + str.tostring(ardt * 10, downsigdig) : nspace + str.tostring(ardt, downsigdig) : wavechoice == 6 ? ardreg > 999 and ardreg <= 9999 ? nspace + str.tostring(ardt * 10, downsigdig) + '\n' + str.tostring(10 * bars_) : nspace + str.tostring(ardt, downsigdig) + '\n' + str.tostring(bars_) : ardreg > 999 and ardreg <= 9999 ? nspace + str.tostring(math.round(ardt)) + '\n' + str.tostring(ardtbar * 10, ardtsigdig) : nspace + str.tostring(ardt, downsigdig) + '\n' + str.tostring(ardtbar, ardtsigdig)) : na : na
uplbl = KO ? toppe and shovol ? label.new(bar_index[limboup[1] + 1], toppe + 1, style=label.style_none, yloc=yloc.abovebar, textcolor=need_manual_calc and shovol_ != 'Show true wave volume' ? colorr : wavechoice == 2 or wavechoice == 3 ? colorc : colorb, size=txtsize, text=shotruvol == false ? (wavechoice == 2 or wavechoice == 3) and calcmult_m and cpvh >= -1 and cpvh <= 3 ? str.tostring(plotvolup, cpvh_) + nspace : arreg < .1 and (mult > 0 or mult < 0) ? 'down' + nspace : arreg > 9999 and (mult > 0 or mult < 0) ? 'up' + nspace : wavechoice != 6 and wavechoice != 7 ? arreg > 999 and arreg <= 9999 ? str.tostring(math.round(ar * 10)) + nspace : str.tostring(math.round(ar)) + nspace : wavechoice == 6 ? arreg > 999 and arreg <= 9999 ? str.tostring(math.round(ar * 10)) + '\n' + str.tostring(10 * bars_) + nspace : str.tostring(math.round(ar)) + '\n' + str.tostring(bars_) + nspace : arreg > 999 and arreg <= 9999 ? str.tostring(math.round(ar * 10)) + '\n' + str.tostring(math.round(10 * ar / bars_)) + nspace : str.tostring(math.round(ar)) + '\n' + str.tostring(math.round(ar / bars_)) : wavechoice != 6 and wavechoice != 7 ? arreg > 999 and arreg <= 9999 ? str.tostring(art * 10, upsigdig) + nspace : str.tostring(art, upsigdig) + nspace : wavechoice == 6 ? arreg > 999 and arreg <= 9999 ? str.tostring(art * 10, upsigdig) + '\n' + str.tostring(10 * bars_) + nspace : str.tostring(art, upsigdig) + '\n' + str.tostring(bars_) + nspace : arreg > 999 and arreg <= 9999 ? str.tostring(art * 10, upsigdig) + '\n' + str.tostring(10 * artbar, artsigdig) + nspace : str.tostring(art, upsigdig) + '\n' + str.tostring(artbar, artsigdig) + nspace) : na : na //size=size.auto,
// wavechoice==8?(ardreg)>999 and (ardreg)<=9999?tostring(round(ard*10))+ " " + tostring(10*deltaclose) + " " + tostring(10*bars_) +"\n" + tostring(round(ard*10/deltaclose)): tostring(round(ard))+ " " + tostring(deltaclose) + " " + tostring(bars_) +"\n" + tostring(round(ard/deltaclose)):
label.set_textalign(dnlbl, text.align_right)
label.set_textalign(uplbl, text.align_right)
// 235 base pre weis/ ord
weisline := line.new(bar_index - begin, pricehloc[begin], bar_index - end, pricehloc[end], width=linewidth, color=KO ? toppe ? colourupwave : colourdownwave : na)
// see #349 for the original notes
var tmult = 0
tmult := timeframe.ismonthly ? 2000 : timeframe.isweekly ? 1000 : timeframe.isdaily ? 300 : r < 10 ? 10 : r < 60 ? 60 : timeframe.isintraday ? 200 : not timeframe.isintraday ? 750 : 500
milliseconds_in_5days = 1000 * 60 * 60 * 24 * tmult // millisecs * secs * min * hours * days
leftborder = timenow - time < milliseconds_in_5days // true or na when false
rightborder = barstate.islast
max = float(na)
max := not leftborder ? na : na(max[1]) ? cpvmult : max[1]
if cpvmult > max // we have a new high
max := cpvmult // change variable "max" to use current bar's high value
max
multval = rightborder ? max[1] : na
var WeisLabel1 = label.new(x=na, y=na, xloc=xloc.bar_time, color=color.white, textcolor=color.black)
var WeisLabel2 = label.new(x=na, y=na, xloc=xloc.bar_time, color=color.white, textcolor=color.black)
// Update the label on the chart's right
var minran_ = string(na)
var minranp = string(na)
wavesizepercent = minrangee / close * 100
//cpvh>=0? cpvd + 1
minran_ := minrangee >= 100 ? '#' : minrangee >= 10 ? '#.#' : minrangee >= 1 ? '#.##' : minrangee >= .1 ? '#.###' : minrangee >= .01 ? '#.####' : minrangee >= .001 ? '#.#####' : minrangee >= .0001 ? '#.######' : minrangee >= .00001 ? '#.#######' : minrangee >= .000001 ? '#.########' : minrangee >= .0000001 ? '#.########' : minrangee >= .00000001 ? '#.##########' : minrangee >= .000000001 ? '#.###########' : minrangee >= .0000000001 ? '#.############' : minrangee >= .00000000001 ? '#.#############' : minrangee >= .000000000001 ? '#.##############' : na //
minranp := wavesizepercent >= 100 ? '#' : wavesizepercent >= 10 ? '#.#' : wavesizepercent >= 1 ? '#.##' : wavesizepercent >= .1 ? '#.###' : wavesizepercent >= .01 ? '#.####' : wavesizepercent >= .001 ? '#.#####' : wavesizepercent >= .0001 ? '#.######' : wavesizepercent >= .00001 ? '#.#######' : wavesizepercent >= .000001 ? '#.########' : wavesizepercent >= .0000001 ? '#.########' : wavesizepercent >= .00000001 ? '#.##########' : wavesizepercent >= .000000001 ? '#.###########' : wavesizepercent >= .0000000001 ? '#.############' : wavesizepercent >= .00000000001 ? '#.#############' : wavesizepercent >= .000000000001 ? '#.##############' : na //
var multfactor = 0.0
var expo = 0.0
// cpvhh=(wavechoice==2 or wavechoice ==3) and cpvh>=0? cpvh + 2:cpvh_new // cpvh_new =(if alternate famult or if not then cpvh)+ multsen +2
// multfactor :=calcmult_m and cpvh>=-1 and cpvh_new<=3?1:pow(10, cpvh_new - 2)
// cpvh:= (wavechoice==2 or wavechoice ==3) and cpvh>=-1 and cpvh<=3?2:cpvh_new //multsen + 2
cpvhh = (wavechoice == 2 or wavechoice == 3) and cpvh >= 0 ? cpvh + 2 : cpvh // cpvh_new =(if alternate famult or if not then cpvh)+ multsen +2
multfactor := calcmult and cpvh >= -1 and cpvh <= 3 ? 1 : math.pow(10, cpvh - multsen)
cpvh := (wavechoice == 2 or wavechoice == 3) and cpvh >= -1 and cpvh <= 3 ? 2 : cpvh //multsen + 2
timeframe_ = timeframe.isintraday ? '- minutes' : timeframe.isdaily ? '- hours' : '- bars in wave'
ran = 0.0
k2 = timeframe.isdaily ? 300 : 1 // if isintraday ? add time to compensate open - time_close
//Rangebartime:= timeframe.isintraday?time_close[1]/60000 - time/60000:timeframe.isdaily?time_close[1]/3600000 - time/3600000:timeframe.isdwm?1:na
run = timeframe.period == '1' ? 1 : timeframe.period == '2' ? 2 : timeframe.period == '3' ? 3 : timeframe.period == '4' ? 4 : timeframe.period == '5' ? 5 : timeframe.period == '6' ? 6 : timeframe.period == '7' ? 7 : timeframe.period == '8' ? 8 : timeframe.period == '9' ? 9 : timeframe.period == '10' ? 10 : timeframe.period == '11' ? 11 : timeframe.period == '12' ? 12 : timeframe.period == '13' ? 13 : timeframe.period == '14' ? 14 : timeframe.period == '15' ? 15 : timeframe.period == '16' ? 16 : timeframe.period == '17' ? 17 : timeframe.period == '18' ? 18 : timeframe.period == '19' ? 19 : timeframe.period == '20' ? 20 : timeframe.period == '21' ? 21 : timeframe.period == '22' ? 22 : timeframe.period == '23' ? 23 : timeframe.period == '24' ? 24 : timeframe.period == '25' ? 25 : timeframe.period == '26' ? 26 : timeframe.period == '27' ? 27 : timeframe.period == '28' ? 28 : timeframe.period == '29' ? 29 : timeframe.period == '30' ? 30 : timeframe.period == '31' ? 31 : timeframe.period == '32' ? 32 : timeframe.period == '33' ? 33 : timeframe.period == '34' ? 34 : timeframe.period == '35' ? 35 : timeframe.period == '36' ? 36 : timeframe.period == '37' ? 37 : timeframe.period == '38' ? 38 : timeframe.period == '39' ? 39 : timeframe.period == '40' ? 40 : timeframe.period == '45' ? 45 : timeframe.period == '60' ? 60 : timeframe.period == '65' ? 65 : timeframe.period == '120' ? 120 : timeframe.period == '130' ? 130 : timeframe.period == '180' ? 180 : timeframe.period == '195' ? 195 : timeframe.period == '225' ? 225 : timeframe.period == '240' ? 240 : timeframe.period == '260' ? 260 : timeframe.period == '480' ? 480 : 0
//ran:= timeframe.isintraday and run<=5 and abs(time_close[1]/60000 - time/60000)>5? abs(time_close[1]/60000 - time/60000) :timeframe.isdaily?time_close[1]/3600000 - time/3600000:timeframe.isdwm?1:na
if barstate.islast and shokey
labelText1 = wavechoice == 1 ? 'Type: Weis volume ' + '\nWeis wave size: ' + str.tostring(minrangee, minran_) + '\nWave size as a percent' + '\nof last close: ' + str.tostring(wavesizepercent, minranp) + '%' + '\nManual Multiplier: ' + str.tostring(cpvhh) + '\nPower Exponent: ' + str.tostring(cpvh - multsen) + '\nMultiply by: ' + str.tostring(multfactor) : wavechoice == 2 ? 'Type: delta price or delta pip ' + '\nWeis wave size: ' + str.tostring(minrangee, minran_) + '\nWave size as a percent' + '\nof last close: ' + str.tostring(wavesizepercent, minranp) + '%' + '\nManual Multiplier: ' + str.tostring(cpvhh) + '\nPower Exponent: ' + str.tostring(cpvh - multsen) + '\nMultiply by: ' + str.tostring(multfactor) : wavechoice == 3 ? 'wave time ' + timeframe_ + '\nWeis wave size: ' + str.tostring(minrangee, minran_) + '\nWave size as a percent' + '\nof last close: ' + str.tostring(wavesizepercent, minranp) + '%' + '\nManual Multiplier: ' + str.tostring(cpvhh) + '\nPower Exponent: ' + str.tostring(cpvh - multsen) + '\nMultiply by: ' + str.tostring(multfactor) : wavechoice == 4 ? 'Weis cumulative volume/delta price ' + '\nWeis wave size: ' + str.tostring(minrangee, minran_) + '\nWave size as a percent' + '\nof last close: ' + str.tostring(wavesizepercent, minranp) + '%' + '\nManual Multiplier: ' + str.tostring(cpvhh) + '\nPower Exponent: ' + str.tostring(cpvh - multsen) + '\nMultiply by:: ' + str.tostring(multfactor) : wavechoice == 5 ? 'Ord style volume ' + '\nWeis wave size: ' + str.tostring(minrangee, minran_) + '\nWave size as a percent' + '\nof last close: ' + str.tostring(wavesizepercent, minranp) + '%' + '\nManual Multiplier: ' + str.tostring(cpvhh) + '\nPower Exponent: ' + str.tostring(cpvh - multsen) + '\nMultiply by: ' + str.tostring(multfactor) : wavechoice == 6 ? 'Weis volume over # bars per wave ' + '\nWeis wave size: ' + str.tostring(minrangee, minran_) + '\nWave size as a percent' + '\nof last close: ' + str.tostring(wavesizepercent, minranp) + '%' + '\nManual Multiplier: ' + str.tostring(cpvhh) + '\nPower Exponent: ' + str.tostring(cpvh - multsen) + '\nMultiply by: ' + str.tostring(multfactor) : wavechoice == 7 ? 'Weis wave volume over Ord style volume ' + '\nWeis wave size: ' + str.tostring(minrangee, minran_) + '\nWave size as a percent' + '\nof last close: ' + str.tostring(wavesizepercent, minranp) + '%' + '\nManual Multiplier: ' + str.tostring(cpvhh) + '\nPower Exponent: ' + str.tostring(cpvh - multsen) + '\nMultiply by: ' + str.tostring(multfactor) : na
label.set_y(id=WeisLabel1, y=close[1])
label.set_x(id=WeisLabel1, x=time + 1800000 * k2) //80)bar_index
//label.set_x(id=WeisLabel1, x=bar_index )//80)bar_index
label.set_text(id=WeisLabel1, text=labelText1)
label.set_style(id=WeisLabel1, style=label.style_label_lower_left)
label.set_textalign(WeisLabel1, text.align_left)
if barstate.islast and shokey
labelText2 = sensitivity == 1 ? 'sensitivity 1' : sensitivity == 2 ? 'sensitivity 2' : sensitivity == 3 ? 'sensitivity 3' : calcmult_a == 6 ? 'alternative auto method' : calcmult_a == 7 ? 'alternative auto method x10' : calcmult ? 'Calculate Automatically' : calcmult == false ? 'Manually set multiplier' : na
label.set_y(id=WeisLabel2, y=close[1])
label.set_x(id=WeisLabel2, x=time + 1800000 * k2) //80)bar_index
label.set_text(id=WeisLabel2, text=labelText2)
label.set_style(id=WeisLabel2, style=label.style_label_upper_left)
label.set_textalign(WeisLabel2, text.align_left)
// plot(lo+minrangee,color=color.red)
// plot(hi-minrangee, color=color.lime)
// plot(close, color=color.black, linewidth=2, style=plot.style_circles)
|
Stock Data Table | https://www.tradingview.com/script/RedHfPnh-Stock-Data-Table/ | valpatrad | https://www.tradingview.com/u/valpatrad/ | 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/
// © valpatrad
//@version=5
indicator('Stock Data Table', 'Stock Data', true)
////////////////////////////
// //
// Menu //
// //
////////////////////////////
//Company
show_sec = input.bool(true, 'Sector', group='Company')
show_ind = input.bool(true, 'Industry', group='Company')
//Correlation
show_indexes = input.bool(true, 'Index / Index', group='Correlation')
show_ticker = input.bool(true, 'Index / Ticker', group='Correlation')
show_len = input.bool(true, 'Length͏͏ ', group='Correlation', inline='Length')
corr_len = input.int(9, '', 1, group='Correlation', inline='Length')
prec = input.int(3, 'Precision ', 1, 4, group='Correlation', inline='Precision')
corr_col = input.string('Green → Red', 'Color gradient ', ['Red → Green', 'Green → Red'], group='Correlation', inline='Color', tooltip='Color gradient from 0 to 1 and from 0 to -1')
//Shares
show_TSO = input.bool(true, 'Total Shares Outstanding', group='Shares')
show_MCap = input.bool(true, 'Market Capitalization', group='Shares', tooltip='Mega Cap ..... $200 billion or more\nLarge Cap ..... Between $10 billion and $200 billion\nMid Cap ....... Between $2 billion and $10 billion\nSmall Cap ..... Between $300 million and $2 billion\nMicro Cap ..... Less than $300 million')
show_FSO = input.bool(true, 'Float', group='Shares')
show_FFMCap = input.bool(true, 'Free-Float Market Cap', group='Shares', inline='FSO')
always_FFMCap = input.bool(false, 'Always', group='Shares', inline='FSO', tooltip='Leave the "Always" option unchecked to show the Float or the Free-Float Market Cap only when the Free-Float Market Cap is different from the Market Cap.')
penny = input.float(5, 'Penny Stocks <', 0, step=0.01, group='Shares', inline='Penny', tooltip='Stocks below this value will be considered Penny Stocks. Set the number to zero if you are not interested in this classification.')
SHR_th = input.bool(true, '', group='Shares', inline='Shares Threshold')
shares_min = input.int(30000000, 'Thresholds ', group='Shares', inline='Shares Threshold')
shares_max = input.int(600000000, '— ', group='Shares', inline='Shares Threshold')
shares_col = input.color(color.new(#FF5252, 35), ' ', group='Shares', inline='Colors')
shares_min_col = input.color(color.new(#FFEB3B, 35), '', group='Shares', inline='Colors')
shares_max_col = input.color(color.new(#4CAF50, 35), '', group='Shares', inline='Colors', tooltip='From the left:\n1) Color before the first threshold\n2) Color from the first threshold\n3) Color from the second threshold')
//ATR
ATR_len = input.int(14, 'Length ', 1, group='Average True Range', inline='ATR Length')
ATR_tf = input.timeframe('', title='Time Frame ', group='Average True Range', inline='ATR TF')
show_ATR = input.bool(true, 'ATR ', group='Average True Range')
ATR_th = input.bool(false, '', group='Average True Range', inline='ATR Threshold')
ATR_min = input.float(0.5, 'Thresholds ', 0.01, step=0.5, group='Average True Range', inline='ATR Threshold')
ATR_max = input.float(15, '— ', 0.01, step=0.5, group='Average True Range', inline='ATR Threshold')
ATR_col = input.color(color.new(#FF5252, 35), ' ', group='Average True Range', inline='ATR Colors')
ATR_min_col = input.color(color.new(#4CAF50, 35), '', group='Average True Range', inline='ATR Colors')
ATR_max_col = input.color(color.new(#FFEB3B, 35), '', group='Average True Range', inline='ATR Colors')
show_ATRP = input.bool(true, 'Normalized ATR', group='Average True Range')
ATRP_th = input.bool(false, '', group='Average True Range', inline='ATRP Threshold')
ATRP_min = input.float(1.75, 'Thresholds ', 0.01, step=0.5, group='Average True Range', inline='ATRP Threshold')
ATRP_max = input.float(5, '— ', 0.01, step=0.5, group='Average True Range', inline='ATRP Threshold')
ATRP_col = input.color(color.new(#FF5252, 35), ' ', group='Average True Range', inline='ATRP Colors')
ATRP_min_col = input.color(color.new(#4CAF50, 35), '', group='Average True Range', inline='ATRP Colors')
ATRP_max_col = input.color(color.new(#FFEB3B, 35), '', group='Average True Range', inline='ATRP Colors')
//Average Daily Volume
show_ADV = input.bool(true, 'Average Daily Volume', group='Average Daily Volume', tooltip='This row will be visible on daily charts only.')
ADV_len = input.int(20, 'Length ', 1, group='Average Daily Volume', inline='ADV Length')
ADV_th = input.bool(true, '', group='Average Daily Volume', inline='ADV Threshold')
ADV_min = input.int(2000000, 'Thresholds ', group='Average Daily Volume', inline='ADV Threshold')
ADV_max = input.int(10000000, '— ', group='Average Daily Volume', inline='ADV Threshold')
ADV_col = input.color(color.new(#FF5252, 35), ' ', group='Average Daily Volume', inline='Colors')
ADV_min_col = input.color(color.new(#FFEB3B, 35), '', group='Average Daily Volume', inline='Colors')
ADV_max_col = input.color(color.new(#4CAF50, 35), '', group='Average Daily Volume', inline='Colors')
//Daily Change %
show_DChg = input.bool(true, 'Daily Change %', group='Daily Change %', tooltip='This row will be visible on daily charts only.')
//Extended Session Change %
show_ExtChg = input.bool(true, 'Extended Session Change %', group='Extended Session Change %', inline='ExtChg')
show_ExtChg_al = input.bool(true, 'Always', group='Extended Session Change %', inline='ExtChg', tooltip='This row will be visible on intraday charts only. Leave the "Always" option checked to show the value even outside the selected time range.')
ExtChg_time_in = input.session('1600-0930', 'Ext. Session ', group='Extended Session Change %', inline='Market Time')
//Pre-Market Volume
show_PMVol = input.bool(true, 'Pre-Market Volume', group='Pre-Market Volume', inline='PM Vol')
show_PMVol_al = input.bool(true, 'Always', group='Pre-Market Volume', inline='PM Vol', tooltip='This row will be visible on intraday charts only. Leave the "Always" option checked to show the value even outside the selected time range.')
PM_time_in = input.session('0400-0930', 'Pre-Market ', group='Pre-Market Volume', inline='PM Time')
PMVol_th = input.bool(true, '', group='Pre-Market Volume', inline='PM Vol Threshold')
PMVol_min = input.int(50000, 'Thresholds ', group='Pre-Market Volume', inline='PM Vol Threshold')
PMVol_max = input.int(1500000, '— ', group='Pre-Market Volume', inline='PM Vol Threshold')
PMVol_col = input.color(color.new(#FF5252, 35), ' ', group='Pre-Market Volume', inline='Colors')
PMVol_min_col = input.color(color.new(#4CAF50, 35), '', group='Pre-Market Volume', inline='Colors')
PMVol_max_col = input.color(color.new(#FFEB3B, 35), '', group='Pre-Market Volume', inline='Colors')
//Table
title_TSO = input.string('SHR', 'Total Shares Outstanding', group='Table', tooltip='Clear the fields to remove the corresponding cell.')
title_FSO = input.string('Float', 'Float', group='Table')
title_ATR = input.string('ATR', 'Average True Range', group='Table')
title_ADV = input.string('ADV', 'Average Daily Volume', group='Table')
title_DChg = input.string('DLY Chg', 'Daily Change %', group='Table')
title_ExtChg = input.string('Ext Chg', 'Extended Session Change %', group='Table')
title_PMVol = input.string('PM Vol', 'Pre-Market Volume', group='Table')
brackets = input.string('Round', 'Brackets', ['Square', 'Round'], group='Table')
invert_corr = input.bool(false, 'Invert Correlation rows', group='Table')
invert_shares = input.bool(false, 'Invert Shares rows', group='Table')
invert_daily = input.bool(false, 'Invert Daily rows', group='Table')
invert_intraday = input.bool(false, 'Invert Intraday rows', group='Table')
sec_col = input.color(#B2B5BE, 'Sector ', group='Table', inline='Line 0')
ind_col = input.color(#B2B5BE, 'Industry ', group='Table', inline='Line 0')
SPY_col = input.color(#C4162E, 'SPY ', group='Table', inline='Line 0')
QQQ_col = input.color(#2750FF, ' QQQ ', group='Table', inline='Line 0')
len_col = input.color(#DDDDDD, 'Correlation Length ', group='Table', inline='Line 1')
ticker_col = input.color(#00FFFF, ' Ticker ', group='Table', inline='Line 1')
MCap_col = input.color(#008EFF, 'Market Cap ', group='Table', inline='Line 2')
FFMCap_col = input.color(#F423FC, ' Free-Float Market Cap', group='Table', inline='Line 2')
no_th_col = input.color(#DDDDDD, 'No-Threshold cells ', group='Table', inline='Line 3')
title_col = input.color(#9598A1, 'Titles ', group='Table', inline='Line 4')
cust_col = input.bool(false, 'Monochromatic Text ', group='Table', inline='Text Color')
in_font = input.string('Default', 'Text Font' , ['Default', 'Monospace'], group='Table')
font = switch in_font
'Default' => font.family_default
'Monospace' => font.family_monospace
monotxt_col = input.color(#B2B5BE, '', group='Table', inline='Text Color')
txt_transp = input.int(0, 'Text Transparency', 0, 100, group='Table')
transp = input.int(70, 'BKGD Transparency', 0, 100, group='Table')
b_width = input.int(1, 'Border Width', 0, group='Table')
in_tab_size = input.string('Normal', 'Size', ['Auto', 'Tiny', 'Small', 'Normal', 'Large', 'Huge'], group='Table')
tab_size = switch in_tab_size
'Auto' => size.auto
'Tiny' => size.tiny
'Small' => size.small
'Normal' => size.normal
'Large' => size.large
'Huge' => size.huge
in_tab_pos = input.string('Top Right', 'Position', ['Top Left', 'Top Center', 'Top Right', 'Middle Left', 'Middle Center', 'Middle Right', 'Bottom Left', 'Bottom Center', 'Bottom Right'], group='Table')
tab_pos = switch in_tab_pos
'Top Left' => position.top_left
'Top Center' => position.top_center
'Top Right' => position.top_right
'Middle Left' => position.middle_left
'Middle Center' => position.middle_center
'Middle Right' => position.middle_right
'Bottom Left' => position.bottom_left
'Bottom Center' => position.bottom_center
'Bottom Right' => position.bottom_right
/////////////////////////////
// //
// Variables //
// //
/////////////////////////////
//Correlation
ID = syminfo.ticker
SPY = ticker.new('AMEX', 'SPY', session.extended)
QQQ = ticker.new('NASDAQ', 'QQQ', session.extended)
SPY_c = request.security(SPY, '', close)
QQQ_c = request.security(QQQ, '', close)
corr_index = ta.correlation(SPY_c, QQQ_c, corr_len)
corr_ticker = ta.correlation(syminfo.prefix == 'NASDAQ' ? QQQ_c : SPY_c, close, corr_len)
bg_col(c) =>
if corr_col == 'Red → Green'
if c <= -0.7
color.from_gradient(c, -1, -0.7, #00FF00, #FFFF00)
else if c > -0.7 and c < -0.35
color.from_gradient(c, -0.7, -0.35, #FFFF00, #FFA500)
else if c > -0.35 and c < 0
color.from_gradient(c, -0.35, 0, #FFA500, #FF0000)
else if c == 0
#FF0000
else if c > 0 and c < 0.35
color.from_gradient(c, 0, 0.35, #FF0000, #FFA500)
else if c > 0.35 and c < 0.7
color.from_gradient(c, 0.35, 0.7, #FFA500, #FFFF00)
else if c >= 0.7
color.from_gradient(c, 0.7, 1, #FFFF00, #00FF00)
else
if c <= -0.7
color.from_gradient(c, -1, -0.7, #FF0000, #FFA500)
else if c > -0.7 and c < -0.35
color.from_gradient(c, -0.7, -0.35, #FFA500, #FFFF00)
else if c > -0.35 and c < 0
color.from_gradient(c, -0.35, 0, #FFFF00, #00FF00)
else if c == 0
#00FF00
else if c > 0 and c < 0.35
color.from_gradient(c, 0, 0.35, #00FF00, #FFFF00)
else if c > 0.35 and c < 0.7
color.from_gradient(c, 0.35, 0.7, #FFFF00, #FFA500)
else if c >= 0.7
color.from_gradient(c, 0.7, 1, #FFA500, #FF0000)
//Shares
TSO = syminfo.shares_outstanding_total
FSO = syminfo.shares_outstanding_float
MCap = TSO * close
FFMCap = FSO * close
cap(c) =>
if c >= 200000000000
'Mega Cap'
else if c >= 10000000000 and c < 200000000000
'Large Cap'
else if c >= 2000000000 and c < 10000000000
'Mid Cap'
else if c >= 300000000 and c < 2000000000
'Small Cap'
else if c < 300000000 and close >= penny
'Micro Cap'
else if c < 300000000 and close < penny
'Penny Stock'
//ATR
ATR = request.security(syminfo.tickerid, ATR_tf, ta.atr(ATR_len))
ATRP = (ATR/close)*100
//Average Daily Volume
D_vol = request.security(syminfo.tickerid, 'D', volume)
ADV = ta.sma(D_vol, ADV_len)
D_vol_Y = request.security(syminfo.tickerid, 'D', volume[1])
ADV_Y = ta.sma(D_vol_Y, ADV_len)
//Daily Change %
D_close = request.security(syminfo.tickerid, 'D', close)
DChg = (D_close-D_close[1])/D_close[1]*100
//Extended Session Change %
Ext_time = time(timeframe.period, ExtChg_time_in)
var float close_1 = na
if na(Ext_time)[1] and not na(Ext_time)
close_1 := close[1]
var float Ext_Chg = na
if not na(Ext_time)
Ext_Chg := (close-close_1)/close_1*100
//Pre-Market Volume
PM_time = time(timeframe.period, PM_time_in)
var float PMVol = na
if na(PM_time)[1] and not na(PM_time)
PMVol := 0
if not na(PM_time)
PMVol := PMVol + volume
//Table
tab = table.new(tab_pos, 4, 11, border_width=b_width)
int clm = 0
int row = 0
float corr = 0.
_info(row, txt, col) =>
clmn = show_ticker or show_indexes ? 0 : 1
table.cell(tab, clmn, row, txt, text_color=color.new(col, txt_transp), text_size=tab_size, bgcolor=color.new(col, transp), text_font_family=font)
table.merge_cells(tab, clmn, row, 3, row)
_index(clm, row, txt, col1, col2) =>
table.cell(tab, clm, row, txt, text_color=cust_col ? color.new(monotxt_col, txt_transp) : syminfo.prefix == 'NASDAQ' ? color.new(col1, txt_transp) : color.new(col2, txt_transp), text_size=tab_size, bgcolor=syminfo.prefix == 'NASDAQ' ? color.new(col1, transp) : color.new(col2, transp), text_font_family=font)
_corr(row, corr) =>
table.cell(tab, 3, row, str.tostring(corr, prec == 4 ? '#.####' : prec == 3 ? '#.###' : prec == 2 ? '#.##' : '#.#'), text_color=cust_col ? color.new(monotxt_col, txt_transp) : color.new(bg_col(corr), txt_transp), text_size=tab_size, bgcolor=color.new(bg_col(corr), transp), text_font_family=font)
_title(txt, clm, row) =>
if txt != ''
table.cell(tab, clm, row, txt == title_ATR and brackets == 'Square' ? txt + '[' + str.tostring(ATR_len) + ']' : txt == title_ATR ? txt + '(' + str.tostring(ATR_len) + ')' : txt == title_ADV and brackets == 'Square' ? txt + '[' + str.tostring(ADV_len) + ']' : txt == title_ADV ? txt + '(' + str.tostring(ADV_len) + ')' : txt, text_color=cust_col ? color.new(monotxt_col, txt_transp) : color.new(title_col, txt_transp), text_size=tab_size, bgcolor=color.new(title_col, transp), text_font_family=font)
_val(clm, row, txt, col) =>
table.cell(tab, clm, row, txt, text_color=cust_col ? color.new(monotxt_col, txt_transp) : color.new(col, txt_transp), text_size=tab_size, bgcolor=color.new(col, transp), text_font_family=font)
th_col(th, v, min, max, c, c_min, c_max) =>
if th
v < min ? c : v >= min and v < max ? c_min : c_max
else
no_th_col
chg_col(c) =>
c > 0 ? color.green : c < 0 ? color.red : color.white
////////////////////////////
// //
// Plot //
// //
////////////////////////////
//Company
if show_sec and not na(syminfo.sector) and not (syminfo.type == 'fund')
row := 0
_info(row, str.tostring(syminfo.sector), sec_col)
if show_ind and not na(syminfo.industry)
row := 1
_info(row, str.tostring(syminfo.industry), ind_col)
//Correlation
if (show_ticker and ID != 'SPY' and ID != 'QQQ' and not na(corr_ticker)) or (show_indexes and not na(corr_index))
row := 2
_index(show_len ? 0 : 1, row, syminfo.prefix == 'NASDAQ' ? 'QQQ' : 'SPY', QQQ_col, SPY_col)
if show_len
_val(1, row, show_len and brackets == 'Square' ? 'r[' + str.tostring(corr_len) + ']' : show_len and brackets == 'Round' ? 'r(' + str.tostring(corr_len) + ')' : na, len_col)
if show_ticker and show_indexes and ID != 'SPY' and ID != 'QQQ' and not na(corr_ticker) and not na(corr_index)
table.merge_cells(tab, show_len ? 0 : 1, row, show_len ? 0 : 1, row+1)
if show_len
table.merge_cells(tab, 1, row, 1, row+1)
if show_indexes and not na(corr_index)
row := show_ticker and invert_corr ? 3 : 2
_index(2, row, syminfo.prefix == 'NASDAQ' ? 'SPY' : 'QQQ', SPY_col, QQQ_col)
_corr(row, corr_index)
if show_ticker and ID != 'SPY' and ID != 'QQQ' and not na(corr_ticker)
row := not show_indexes or invert_corr ? 2 : 3
_val(2, row, str.tostring(syminfo.ticker), ticker_col)
_corr(row, corr_ticker)
//Shares
if not na(TSO)
if show_TSO or show_MCap
row := invert_shares ? 5 : 4
_title(title_TSO, 1, row)
if show_TSO
_val(2, row, str.tostring(TSO, format.volume), th_col(SHR_th, TSO, shares_min, shares_max, shares_col, shares_min_col, shares_max_col))
if not show_MCap
table.merge_cells(tab, 2, row, 3, row)
if show_MCap
clm := not show_TSO ? 2 : 3
table.merge_cells(tab, clm, row, 3, row)
_val(clm, row, str.tostring(cap(MCap)), MCap_col)
if not na(FSO)
if always_FFMCap or cap(MCap) != cap(FFMCap)
if show_FSO or show_FFMCap
row := invert_shares ? 4 : 5
_title(title_FSO, 1, row)
if show_FSO
_val(2, row, str.tostring(FSO, format.volume), th_col(SHR_th, FSO, shares_min, shares_max, shares_col, shares_min_col, shares_max_col))
if not show_FFMCap
table.merge_cells(tab, 2, row, 3, row)
if show_FFMCap
clm := not show_FSO ? 2 : 3
table.merge_cells(tab, clm, row, 3, row)
_val(clm, row, str.tostring(cap(FFMCap)), FFMCap_col)
//ATR
if not na(ATR)
if show_ATR or show_ATRP
row := 6
_title(title_ATR, show_ATR and show_ATRP ? 1 : 2, row)
if show_ATR
_val(show_ATRP ? 2 : 3, row, str.tostring(ATR, '#.##'), th_col(ATR_th, ATR, ATR_min, ATR_max, ATR_col, ATR_min_col, ATR_max_col))
if show_ATRP
_val(3, row, str.tostring(ATRP, format.percent), th_col(ATRP_th, ATRP, ATRP_min, ATRP_max, ATRP_col, ATRP_min_col, ATRP_max_col))
//Average Daily Volume
if timeframe.isdaily
if show_ADV and not na(ADV)
row := invert_daily ? 8 : 7
_title(title_ADV, 2, row)
_val(3, row, str.tostring(ADV, format.volume), th_col(ADV_th, ADV, ADV_min, ADV_max, ADV_col, ADV_min_col, ADV_max_col))
//Daily Change %
if show_DChg and not na(DChg)
row := invert_daily ? 7 : 8
_title(title_DChg, 2, row)
_val(3, row, DChg > 0 ? '+' + str.tostring(DChg, format.percent) : str.tostring(DChg, format.percent), chg_col(DChg))
//Extended Session Change %
if timeframe.isintraday
if show_ExtChg and not na(Ext_Chg)
if not na(Ext_time) or (show_ExtChg_al and na(Ext_time))
row := invert_intraday ? 10 : 9
_title(title_ExtChg, 2, row)
_val(3, row, Ext_Chg > 0 ? '+' + str.tostring(Ext_Chg, format.percent) : str.tostring(Ext_Chg, format.percent), chg_col(Ext_Chg))
//Pre-Market Volume
if show_PMVol and not na(PMVol)
if not na(PM_time) or (show_PMVol_al and na(PM_time))
row := invert_intraday ? 9 : 10
_title(title_PMVol, 2, row)
_val(3, row, str.tostring(PMVol, format.volume), th_col(PMVol_th, PMVol, PMVol_min, PMVol_max, PMVol_col, PMVol_min_col, PMVol_max_col)) |
Fibonacci Volatility Bands | https://www.tradingview.com/script/V7mbn1g3-Fibonacci-Volatility-Bands/ | Sofien-Kaabar | https://www.tradingview.com/u/Sofien-Kaabar/ | 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/
// © Sofien-Kaabar
//@version=5
indicator("Fibonacci Volatility Bands", overlay = true)
first_boll_upper = ta.sma(high, 5) + (ta.stdev(high, 5) * 2)
second_boll_upper = ta.sma(high, 8) + (ta.stdev(high, 8) * 2)
third_boll_upper = ta.sma(high, 13) + (ta.stdev(high, 13) * 2)
fourth_boll_upper = ta.sma(high, 21) + (ta.stdev(high, 21) * 2)
fifth_boll_upper = ta.sma(high, 34) + (ta.stdev(high, 34) * 2)
sixth_boll_upper = ta.sma(high, 55) + (ta.stdev(high, 55) * 2)
seventh_boll_upper = ta.sma(high, 89) + (ta.stdev(high, 89) * 2)
eigth_boll_upper = ta.sma(high, 144) + (ta.stdev(high, 144) * 2)
av_boll_upper = (first_boll_upper +
second_boll_upper +
third_boll_upper +
fourth_boll_upper +
fifth_boll_upper +
sixth_boll_upper +
seventh_boll_upper +
eigth_boll_upper) / 8
first_boll_lower = ta.sma(low, 5) - (ta.stdev(low, 5) * 2)
second_boll_lower = ta.sma(low, 8) - (ta.stdev(low, 8) * 2)
third_boll_lower = ta.sma(low, 13) - (ta.stdev(low, 13) * 2)
fourth_boll_lower = ta.sma(low, 21) - (ta.stdev(low, 21) * 2)
fifth_boll_lower = ta.sma(low, 34) - (ta.stdev(low, 34) * 2)
sixth_boll_lower = ta.sma(low, 55) - (ta.stdev(low, 55) * 2)
seventh_boll_lower = ta.sma(low, 89) - (ta.stdev(low, 89) * 2)
eigth_boll_lower = ta.sma(low, 144) - (ta.stdev(low, 144) * 2)
av_boll_lower = (first_boll_lower +
second_boll_lower +
third_boll_lower +
fourth_boll_lower +
fifth_boll_lower +
sixth_boll_lower +
seventh_boll_lower +
eigth_boll_lower) / 8
plot(av_boll_lower, color = color.aqua)
plot(av_boll_upper, color = color.purple) |
Move Magnitude Visualizer (beta) | https://www.tradingview.com/script/kmzVh831-Move-Magnitude-Visualizer-beta/ | Electrified | https://www.tradingview.com/u/Electrified/ | 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/
// © Electrified
//@version=5
indicator("Move Magnitude Visualizer", shorttitle = "MMV", overlay = true, max_bars_back = 2000)
var samples = input.int(1200, "Samples", 50, 2000, 50, tooltip = "The number of bars back to begin sampling. Reduce this number if the script takes to long.")
var maxLen = math.floor(samples * input.float(5, "Max Length (%)", 0.1, 100, 1, tooltip = "The maximum length as a percentage of the total samples.") / 100)
var minLen = input.int(4, "Min Length", 1)
var bar = -1
bar += 1
calculateSD(float[] data, float mean) =>
sumSquaredDiff = 0.0
for e in data
sumSquaredDiff += math.pow(e - mean, 2)
math.sqrt(sumSquaredDiff / array.size(data))
////
filteredMean(float[] data, float max) =>
sum = 0.0
count = 0
if max < 0
for e in data
if e > max
sum += e
count += 1
else
for e in data
if e < max
sum += e
count += 1
[sum, count]
calculateSD(float[] data, float mean, int count, float max) =>
sumSquaredDiff = 0.0
if max < 0
for e in data
if e > max
sumSquaredDiff += math.pow(e - mean, 2)
else
for e in data
if e < max
sumSquaredDiff += math.pow(e - mean, 2)
math.sqrt(sumSquaredDiff / count)
////
getDeviation(float d, int len) =>
var data = array.new_float()
var mean = 0.0
var std = 0.0
// don't calculate or store unnecessary data.
if d != 0 and bar > last_bar_index - samples
array.push(data, d)
if array.size(data) > samples
array.shift(data)
m = array.avg(data)
sign = (m < 0 ? -1 : 1)
s = calculateSD(data, m) * sign
max = m + s * 4
[sum, count] = filteredMean(data, max)
mean := sum / count
std := calculateSD(data, mean, count, max) * sign
[mean, std]
////
getDeviationUp(int len) =>
lo = low[len*2]
d = math.max(high[len] - lo, 0) / lo
getDeviation(d, len)
////
getDeviationDn(int len) =>
hi = high[len*2]
d = math.min(low[len] - hi, 0) / hi
getDeviation(d, len)
////
var d3color = input.color(color.new(color.red, 50), "D3", "Level 3", group = "Deviation Lines")
var d2color = input.color(color.new(color.orange, 50), "D2", "Level 2", group = "Deviation Lines")
var d1color = input.color(color.new(color.yellow, 50), "D1", "Level 2", group = "Deviation Lines")
var upLines = array.new_line(maxLen + 1, na)
var dnLines = array.new_line(maxLen + 1, na)
maxUp = 0.0
maxDn = 0.0
for i = minLen to maxLen
[upM, upS] = getDeviationUp(i)
[dnM, dnS] = getDeviationDn(i)
// Minimize processing to recent.
if bar > last_bar_index - maxLen * 3
upLine_prev = array.get(upLines, i)
upline_prev_lo = na(upLine_prev) ? na : line.get_y1(upLine_prev)
upline_prev_hi = na(upLine_prev) ? na : line.get_y2(upLine_prev)
lo = low[i]
if high < upline_prev_hi ? lo > upline_prev_lo : false
if maxUp > (upline_prev_hi - upline_prev_lo) / upline_prev_lo
line.delete(upLine_prev)
array.set(upLines, i, na)
upLine_prev
else
up1 = upM + upS
up2 = up1 + upS
up3 = up2 + upS
up = math.max(high - lo, 0) / lo
upLine = if up > maxUp
maxUp := up
if up > up3
line.new(bar - i, lo, bar, high, color = d3color, width = 4)
else if up > up2
line.new(bar - i, lo, bar, high, color = d2color, width = 2)
else if up > up1
line.new(bar - i, lo, bar, high, color = d1color, width = 1, style = line.style_dotted)
else
na
else
na
line.delete(upLine_prev)
array.set(upLines, i, upLine)
dnLine_prev = array.get(dnLines, i)
dnLine_prev_hi = na(dnLine_prev) ? na : line.get_y1(dnLine_prev)
dnLine_prev_lo = na(dnLine_prev) ? na : line.get_y2(dnLine_prev)
hi = high[i]
if low > dnLine_prev_lo ? hi < dnLine_prev_hi : false
if maxDn < (dnLine_prev_lo - dnLine_prev_hi) / dnLine_prev_hi
line.delete(dnLine_prev)
array.set(dnLines, i, na)
dnLine_prev
else
dn1 = dnM + dnS
dn2 = dn1 + dnS
dn3 = dn2 + dnS
dn = math.min(low - hi, 0) / hi
dnLine = if dn < maxDn
maxDn := dn
if dn < dn3
line.new(bar - i, hi, bar, low, color = d3color, width = 4)
else if dn < dn2
line.new(bar - i, hi, bar, low, color = d2color, width = 2)
else if dn < dn1
line.new(bar - i, hi, bar, low, color = d1color, width = 1, style = line.style_dotted)
else
na
else
na
line.delete(dnLine_prev)
array.set(dnLines, i, dnLine)
|
Smart QQE Mod | https://www.tradingview.com/script/X72V8xjH-Smart-QQE-Mod/ | traderharikrishna | https://www.tradingview.com/u/traderharikrishna/ | 578 | 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/
// © traderharikrishna
//@version=5
indicator("Smart QQE",overlay=true)
// Credits to Glaz
// Rescaled for overlay by @traderharikrishna
// Code By Glaz
// Modifications:
// Added Columns to show when signal is outside of Thresh Hold Channnel.
// Set default Parameters to match QQE Cross Alert indicator.
//
RSI_Period = input(14, title='RSI Length')
SF = input(5, title='RSI Smoothing')
QQE = input(4.238, title='Fast QQE Factor')
ThreshHold = input(10, title='Thresh-hold')
//
sQQEx = input(false, title='Show Smooth RSI, QQE Signal crosses')
sQQEz = input(false, title='Show Smooth RSI Zero crosses')
sQQEc = input(false, title='Show Smooth RSI Thresh Hold Channel Exits')
ma_type = input.string(title='MA Type', defval='EMA', options=['ALMA', 'EMA', 'DEMA', 'TEMA', 'WMA', 'VWMA', 'SMA', 'SMMA', 'HMA', 'LSMA', 'PEMA'])
lsma_offset = input.int(defval=0, title='* Least Squares (LSMA) Only - Offset Value', minval=0)
alma_offset = input.float(defval=0.85, title='* Arnaud Legoux (ALMA) Only - Offset Value', minval=0, step=0.01)
alma_sigma = input.int(defval=6, title='* Arnaud Legoux (ALMA) Only - Sigma Value', minval=0)
inpDrawBars = input(true, title='color bars?')
ma(type, src, len) =>
float result = 0
if type == 'SMA' // Simple
result := ta.sma(src, len)
result
if type == 'EMA' // Exponential
result := ta.ema(src, len)
result
if type == 'DEMA' // Double Exponential
e = ta.ema(src, len)
result := 2 * e - ta.ema(e, len)
result
if type == 'TEMA' // Triple Exponential
e = ta.ema(src, len)
result := 3 * (e - ta.ema(e, len)) + ta.ema(ta.ema(e, len), len)
result
if type == 'WMA' // Weighted
result := ta.wma(src, len)
result
if type == 'VWMA' // Volume Weighted
result := ta.vwma(src, len)
result
if type == 'SMMA' // Smoothed
w = ta.wma(src, len)
result := na(w[1]) ? ta.sma(src, len) : (w[1] * (len - 1) + src) / len
result
if type == 'HMA' // Hull
result := ta.wma(2 * ta.wma(src, len / 2) - ta.wma(src, len), math.round(math.sqrt(len)))
result
if type == 'LSMA' // Least Squares
result := ta.linreg(src, len, lsma_offset)
result
if type == 'ALMA' // Arnaud Legoux
result := ta.alma(src, len, alma_offset, alma_sigma)
result
if type == 'PEMA'
// Copyright (c) 2010-present, Bruno Pio
// Copyright (c) 2019-present, Alex Orekhov (everget)
// Pentuple Exponential Moving Average script may be freely distributed under the MIT license.
ema1 = ta.ema(src, len)
ema2 = ta.ema(ema1, len)
ema3 = ta.ema(ema2, len)
ema4 = ta.ema(ema3, len)
ema5 = ta.ema(ema4, len)
ema6 = ta.ema(ema5, len)
ema7 = ta.ema(ema6, len)
ema8 = ta.ema(ema7, len)
pema = 8 * ema1 - 28 * ema2 + 56 * ema3 - 70 * ema4 + 56 * ema5 - 28 * ema6 + 8 * ema7 - ema8
result := pema
result
result
src = input(close, title='RSI Source')
//
//
Wilders_Period = RSI_Period * 2 - 1
Rsi = ta.rsi(src, RSI_Period)
RsiMa = ma(ma_type, Rsi, SF)
AtrRsi = math.abs(RsiMa[1] - RsiMa)
MaAtrRsi = ma(ma_type, AtrRsi, Wilders_Period)
dar = ma(ma_type, MaAtrRsi, Wilders_Period) * QQE
longband = 0.0
shortband = 0.0
trendx = 0
DeltaFastAtrRsi = dar
RSIndex = RsiMa
newshortband = RSIndex + DeltaFastAtrRsi
newlongband = RSIndex - DeltaFastAtrRsi
longband := RSIndex[1] > longband[1] and RSIndex > longband[1] ? math.max(longband[1], newlongband) : newlongband
shortband := RSIndex[1] < shortband[1] and RSIndex < shortband[1] ? math.min(shortband[1], newshortband) : newshortband
cross_1 = ta.cross(longband[1], RSIndex)
trendx := ta.cross(RSIndex, shortband[1]) ? 1 : cross_1 ? -1 : nz(trendx[1], 1)
FastAtrRsiTL = trendx == 1 ? longband : shortband
//
// Find all the QQE Crosses
QQExlong = 0
QQExlong := nz(QQExlong[1])
QQExshort = 0
QQExshort := nz(QQExshort[1])
QQExlong := FastAtrRsiTL < RSIndex ? QQExlong + 1 : 0
QQExshort := FastAtrRsiTL > RSIndex ? QQExshort + 1 : 0
// Zero cross
QQEzlong = 0
QQEzlong := nz(QQEzlong[1])
QQEzshort = 0
QQEzshort := nz(QQEzshort[1])
QQEzlong := sQQEz and RSIndex >= 50 ? QQEzlong + 1 : 0
QQEzshort := sQQEz and RSIndex < 50 ? QQEzshort + 1 : 0
//
// Thresh Hold channel Crosses give the BUY/SELL alerts.
QQEclong = 0
QQEclong := nz(QQEclong[1])
QQEcshort = 0
QQEcshort := nz(QQEcshort[1])
QQEclong := sQQEc and RSIndex > 50 + ThreshHold ? QQEclong + 1 : 0
QQEcshort := sQQEc and RSIndex < 50 - ThreshHold ? QQEcshort + 1 : 0
hcolor = RsiMa - 50 > ThreshHold ? color.green : RsiMa - 50 < 0 - ThreshHold ? color.red : color.orange
//EOF
bgc = RsiMa - 50 > ThreshHold ? color.rgb(7, 196, 243) : Rsi - 50 < 0 - ThreshHold ? color.rgb(247, 4, 117) : color.orange
barcolor(inpDrawBars ? bgc : na)
rsima=input.int(50,'RSI 100 level' )
orsi=ta.rsi(close,RSI_Period)
adjrsi=close+ta.atr(100)*orsi/100
//rma=ta.ema(adjrsi,rsima)
rsimatype=input.string('SMA',options=['EMA','HMA','SMA','WMA','RMA','VWMA'],title='RSI MA Type')
rma=rsimatype=='RMA'?ta.rma(adjrsi,rsima):rsimatype=='HMA'?ta.hma(adjrsi,rsima):rsimatype=='SMA'?ta.sma(adjrsi,rsima):rsimatype=='WMA'?ta.wma(adjrsi,rsima):rsimatype=='VWMA'?ta.vwma(adjrsi,rsima):ta.ema(adjrsi,rsima)
rsi100=rma+ta.atr(100)*(50/10)
rsi0=rma-ta.atr(100)*(50/10)
r100=plot(rsi100,linewidth=4,color=color.red,title='RSI100')
r0=plot(rsi0,linewidth=4,color=color.rgb(1, 165, 70),title='RSI0')
rsi90=rma+ta.atr(100)*(30/10)
rsi10=rma-ta.atr(100)*(30/10)
r90=plot(rsi90,linewidth=2,color=color.red,title='RSI90')
r10=plot(rsi10,linewidth=2,color=color.rgb(1, 165, 70),title='RSI10')
fill(r100,r90,color=color.rgb(255, 82, 82, 79),title='Overbought')
fill(r10,r0,color=color.rgb(44, 248, 3, 79),title='Oversold')
r2=plot(rma,color=open>rma?#00ff00:open<rma?#ff0000:#f1e20e,title='RSI-50 Level',linewidth=2) //mid band
rsim=rma+ta.atr(100)*(RsiMa - 50)/10
frsim=rma+ta.atr(100)*(FastAtrRsiTL - 50)/10
o8=plot(rsim, color=#62f70bf5, title='QQE RSI',linewidth=2) //rsima
o2=plot(frsim, title='Fast RSI',color=#f30303,linewidth=2) //fast rsima
bgc2 = RsiMa - 50 > FastAtrRsiTL - 50 ? #144e055e : #8603035b
fill(o8,o2,color=bgc2,title='QQE Trend')
//thu=rma+ta.atr(100)*10/10
//thl=rma-ta.atr(100)*10/10
//thup=plot(thu, title='Threshold+',color=#000000)
//thlo=plot(thl, title='Threshold-',color=#000000)
//fill(thup,thlo,color=color.rgb(14, 17, 46, 87),title='Threshold Band') //threshold fill
qqeLong = QQExlong == 1 ? frsim: na
qqeShort = QQExshort == 1 ? frsim: na
plotshape(qqeLong, title="QQE long", text="Long", textcolor=color.new(color.white,0), style=shape.labelup, location=location.belowbar, color=color.new(#216d1f, 0), size=size.auto)
plotshape(qqeShort, title="QQE short", text="Short", textcolor=color.new(color.white,0), style=shape.labeldown, location=location.abovebar, color=#ff0000, size=size.auto)
// QQE exit from Thresh Hold Channel
plotshape(sQQEc and QQEclong == 1 ? rsim : na, title='QQE XC Over Channel', style=shape.diamond, location=location.absolute, color=color.new(color.olive, 0), size=size.auto, offset=0)
plotshape(sQQEc and QQEcshort == 1 ? rsim : na, title='QQE XC Under Channel', style=shape.diamond, location=location.absolute, color=color.new(color.red, 0), size=size.auto, offset=0)
// QQE crosses
plotshape(sQQEx and QQExlong == 1 ? frsim : na, title='QQE XQ Cross Over', style=shape.circle, location=location.absolute, color=color.new(color.lime, 0), size=size.auto, offset=-1)
plotshape(sQQEx and QQExshort == 1 ? frsim : na, title='QQE XQ Cross Under', style=shape.circle, location=location.absolute, color=color.new(color.blue, 0), size=size.auto, offset=-1)
// Signal crosses zero line
plotshape(sQQEz and QQEzlong == 1 ? rsim : na, title='QQE XZ Zero Cross Over', style=shape.square, location=location.absolute, color=color.new(color.aqua, 0), size=size.auto, offset=0)
plotshape(sQQEz and QQEzshort == 1 ? rsim : na, title='QQE XZ Zero Cross Under', style=shape.square, location=location.absolute, color=color.new(color.fuchsia, 0), size=size.auto, offset=0)
alertcondition(qqeLong,title = 'SMART QQE LONG',message='SMART QQE LONG')
alertcondition(qqeShort,title = 'SMART QQE SHORT',message='SMART QQE SHORT')
show200ma=input.bool(false,'Show 200MA')
ma200=input.int(200,title='MovingAverage 200')
matype200=input.string('SMA',options=['EMA','HMA','SMA','WMA','RMA','VWMA'],title='MA 200 Type')
mao200=matype200=='RMA'?ta.rma(close,ma200):matype200=='HMA'?ta.hma(close,ma200):matype200=='SMA'?ta.sma(close,ma200):matype200=='WMA'?ta.wma(close,ma200):matype200=='VWMA'?ta.vwma(close,ma200):ta.ema(close,ma200)
plot(show200ma?mao200:na,title='MovingAverage 200',linewidth=3)
///////////////////////MA RIBBON
showma=input.bool(false,'Show MA ribbon')
macoloro=input.color(color.new(#ff0000, 0),'MA Down Color')
macolorc=input.color(color.new(#62ff42, 0),'MA Up Color')
malen=input(60,'Moving Averge Length')
matype=input.string('HMA',options=['EMA','HMA','SMA','WMA','RMA','VWMA'],title='MA Type')
mao=matype=='RMA'?ta.rma(open,malen):matype=='HMA'?ta.hma(open,malen):matype=='SMA'?ta.sma(open,malen):matype=='WMA'?ta.wma(open,malen):matype=='VWMA'?ta.vwma(open,malen):ta.ema(open,malen)
mac=matype=='RMA'?ta.rma(close,malen):matype=='HMA'?ta.hma(close,malen):matype=='SMA'?ta.sma(close,malen):matype=='WMA'?ta.wma(close,malen):matype=='VWMA'?ta.vwma(close,malen):ta.ema(close,malen)
v=plot(showma?mao:na,color=macoloro,linewidth=1,display=display.none)
y=plot(showma?mac:na,color=macolorc,linewidth=1,display=display.none)
fill(v,y,color=mao>mac?macoloro:macolorc,title='MA Ribbon')
|
TheATR™: Volatility Extremes (VolEx) | https://www.tradingview.com/script/rLFHjHvA-TheATR-Volatility-Extremes-VolEx/ | theATR | https://www.tradingview.com/u/theATR/ | 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/
// © theATR
//@version=5
indicator("TheATR™: Volatility Extremes", "VolEx(TheATR™)")
//User has to agree to have the indi loading on the chart.
//{
var user_consensus = input.string(defval="", title="By typing 'Agree' you acknowledge the understanding about the fact 'TheATR™: Volatility Extremes' (or 'VolEx(TheATR™)') doesn't aim and/or intend to provide any financial advice, as of its nature of being an educational tool.\n © TheATR", confirm = true, group="consensus")
var valid = false
if user_consensus == "Agree"
valid := true
else
valid := false
var label lbl_agree_err = na
if not valid
runtime.error("'Agree' to the consensus policy first in order to display the Indicator.")
//}
//--Settings
//{
i_volex_t = input.string("%", "Extremes Detection Parameter", ["%", "St.Dev."], inline = 'sett00')
i_volex_lb = input.int(100, "Lookback", minval = 10, inline='sett01')
i_volex_l = input.int(14, "ATR Base Lenght", minval = 2, inline='sett01')
i_volex_ptop = input.float(90.0, "↑ '%': % Thresholds: Top", minval = 60.0, maxval = 100.0, inline = 'sett02')
i_volex_pbot = input.float(10.0, "Bottom", minval = 0.0, maxval = 40.0, inline = 'sett02')
i_volex_stdev = input.float(2.0, "↑ 'St.Dev.': St.Dev. Factor", minval = 0.25, inline = 'step03')
i_volex_stndcol = input.color(color.blue, "Volatility Colors:\nStandard ", inline = 'settcols0')
i_volex_highcol = input.color(color.yellow, "Extremely High ", inline = 'settcols1')
i_volex_lowcol = input.color(color.rgb(161, 118, 0), "Extremely Low ", inline = 'settcols2')
//}
//--Calcs
//{
var volex_atr = 0.0
volex_atr := ta.atr(i_volex_l)
var volex_ptop = 0.0, var volex_pbot = 0.0
volex_ptop := ta.percentile_linear_interpolation(volex_atr, i_volex_lb, i_volex_ptop)
volex_pbot := ta.percentile_linear_interpolation(volex_atr, i_volex_lb, i_volex_pbot)
var volex_stdevtop = 0.0, var volex_stdevbot = 0.0
volex_stdevtop := ta.sma(volex_atr, i_volex_lb) + i_volex_stdev * ta.stdev(volex_atr, i_volex_lb)
volex_stdevbot := ta.sma(volex_atr, i_volex_lb) - i_volex_stdev * ta.stdev(volex_atr, i_volex_lb)
var volex_topf = 0.0, var volex_botf = 0.0
volex_topf := i_volex_t == "%" ? volex_ptop:volex_stdevtop
volex_botf := i_volex_t == "%" ? volex_ptop:volex_stdevbot
var volex_high = false, var volex_low = false
volex_high := volex_atr > volex_topf
volex_low := volex_atr < volex_botf
//}
//--Plots
//{
var color volex_col = na
volex_col := volex_high?i_volex_highcol:volex_low?i_volex_lowcol:i_volex_stndcol
plot(valid?volex_atr:na, "ATR", volex_col, 1)
barcolor(valid and volex_high?i_volex_highcol:na)
barcolor(valid and volex_low?i_volex_lowcol:na)
//}
|
Expansion Finder by nnam | https://www.tradingview.com/script/jED0CeFd-Expansion-Finder-by-nnam/ | nnamdert | https://www.tradingview.com/u/nnamdert/ | 87 | 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/
// © nnamdert
//@version=5
indicator(title="Expansion Finder by nnam", overlay = true, max_bars_back = 500)
range_to_calculate = input.int(defval = 14, title = 'Range of bars to calculate average', tooltip = 'default is 14')
expansion_multiplier = input.float(defval = 1.2, title = 'Expansion Multiplier', step = 0.1, tooltip = 'default is 1.2')
expansion_color = input.color(color.new(color.maroon, 0), title = 'Expansion Color')
contraction_color = input.color(color.new(color.teal, 0), title = 'Contraction Color')
contraction_bar_color = input.color(color.new(#7babd1, 0), title = 'Contraction Bar Color')
bar_color = input.color(color.new(color.yellow, 0), title = 'Expansion Bar Color')
BarRange() =>
high - low
avgRange = ta.ema(BarRange(), range_to_calculate)
rangeColor = if BarRange() > (avgRange * expansion_multiplier)
expansion_color
else
contraction_color
barcolor(BarRange() > (avgRange * expansion_multiplier) ? color.new(bar_color, 0) : color.new(contraction_bar_color, 0))
//for overlay - false
//plot(BarRange(), style=plot.style_columns,
// color=color.new(rangeColor, 30), title="Bar Range")
//plot(avgRange, color=color.orange, linewidth=1, title="Average Range")
|
Price & Percentage Change Label | https://www.tradingview.com/script/tXGdrETm-Price-Percentage-Change-Label/ | MYNAMEISBRANDON | https://www.tradingview.com/u/MYNAMEISBRANDON/ | 35 | 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/
// © MYNAMEISBRANDON
//@version=5
indicator("Price Label", "Price Label", overlay=true)
var string maGroup0 = '----------------------------Timeframe Options----------------------------'
resInputMA = input.timeframe(title='MA/RSI/CMO Timeframe', defval='', group=maGroup0)
int in_CMO_length = input.int(title="CMO Length", defval=25, minval=1, group=maGroup0)
int in_RSI_length = input.int(title="RSI Length", defval=14, minval=1, group=maGroup0)
in_volumeTF_daily = input.timeframe(title='Volume Timeframe=Daily', defval='1D', group=maGroup0)
show_ma_timeframe = input.bool(true, "Enable MA timeframe label", group=maGroup0)
resInputMA1 = input.timeframe(title='Conviction Arrows Timeframe', defval='', group=maGroup0)
_get(res, src) =>
data = res == timeframe.period ? src : src[1]
request.security(syminfo.tickerid, res, data, lookahead=barmerge.lookahead_on)
get_timeframe_title(simple string tf = "") =>
chartTf = timeframe.isminutes == true and timeframe.multiplier > 59 ? (timeframe.multiplier/60 % 2 == 0 ? str.tostring(timeframe.multiplier/60)+"h" : str.tostring(timeframe.multiplier)+"m") : timeframe.isminutes == true ? str.tostring(timeframe.multiplier)+"m" : timeframe.period
result = show_ma_timeframe ? (tf == "" ? "" : request.security(syminfo.tickerid, tf, chartTf)) : ""
_getMany(res, src1, src2, src3, src4, src5) =>
data1 = src1[1]
data2 = src2[1]
data3 = src3[1]
data4 = src4[1]
data5 = src5[1]
if res == timeframe.period
data1 := src1
data2 := src2
data3 := src3
data4 := src4
data5 := src5
[out1, out2, out3, out4, out5] = request.security(syminfo.tickerid, res, [data1, data2, data3, data4, data5], lookahead=barmerge.lookahead_on)
[out1, out2, out3, out4, out5]
//_get2(res, src) =>
//out = request.security(syminfo.tickerid, res, src[barstate.isrealtime ? 1 : 0], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off)
//out
_get2(res, src) =>
request.security(syminfo.tickerid, res, src[barstate.isrealtime ? 1 : 0], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off)
//_get3(res, src) =>
//out = request.security(syminfo.tickerid, res, src[barstate.isrealtime ? 1 : 0], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off)
//out
_get3(res, src) =>
request.security(syminfo.tickerid, res, src[barstate.isrealtime ? 1 : 0], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off)
labels = label.all
// Load all labels generated by this script
labelPadding = " "
labelPadding1 = " "
LabelPadding_Above_Below = " "
labelPadding13_48 = " "
labelPadding100_200 = " "
labelPadding_volume = " "
ma(formula, source, length) =>
switch formula
"" => ta.ema(source, length)
var string maGroup7 = '----------------------------Moving Average 7----------------------------'
enableMA7 = input.bool(true, "Enable MA", group=maGroup7)
enableMA7Label = input.bool(true, "Enable MA label", group=maGroup7)
show_ma_prices7 = input.bool(true, "Enable price", group=maGroup7)
ma7Formula = input.string("", options=['', 'HMA', 'SMA','SWMA','RMA','VWAP','VWMA','WMA', 'ZLEMA', 'DEMA', 'TEMA', 'ALMA', 'ZLSMA'], title="Formula", group=maGroup7)
ma7Length = input.int(100,"Length", group=maGroup7)
distance7 = input.int(0, "MA offset", group=maGroup7)
ma7Color = input.color(color.rgb(120, 216, 82, 16), "Color", group=maGroup7)
ma7Text = str.tostring(ma7Formula) + ' ' + str.tostring(ma7Length)
ma7 = _get(resInputMA, ma(ma7Formula, close, ma7Length))
ma7p = plot(ma7, title="7) EMA 100", color=ma7Color, display=display.none)
showMA7 = enableMA7 ? display.all : display.none
MAtimeframe7Text = get_timeframe_title(resInputMA)
MA7labelXPos = bar_index + math.round(ta.change(bar_index)*distance7)
MA7Price = show_ma_prices7 ? " - "+str.tostring(math.round_to_mintick(ma7)) : ""
ma7LabelText = MAtimeframe7Text == "" ? labelPadding100_200+ma7Formula+" "+str.tostring(ma7Length)+MA7Price : labelPadding100_200+ma7Formula+" "+str.tostring(ma7Length)+" ("+MAtimeframe7Text+")"+MA7Price
var string maGroup9 = '----------------------------Moving Average 9----------------------------'
enableMA9 = input.bool(true, "Enable MA", group=maGroup9)
enableMA9Label = input.bool(true, "Enable MA label", group=maGroup9)
show_ma_prices9 = input.bool(true, "Enable price", group=maGroup9)
ma9Formula = input.string("", options=['', 'HMA', 'SMA','SWMA','RMA','VWAP','VWMA','WMA', 'ZLEMA', 'DEMA', 'TEMA', 'ALMA', 'ZLSMA'], title="Formula", group=maGroup9)
ma9Length = input.int(200,"Length", group=maGroup9)
distance9 = input.int(0, "MA offset", group=maGroup9)
ma9Color = input.color(color.rgb(221, 73, 73), "Color", group=maGroup9)
ma9Text = str.tostring(ma9Formula) + ' ' + str.tostring(ma9Length)
ma9 = _get(resInputMA, ma(ma9Formula, close, ma9Length))
ma9p = plot(ma9, title="9) EMA 200", color=ma9Color, display=display.none)
showMA9 = enableMA9 ? display.all : display.none
MAtimeframe9Text = get_timeframe_title(resInputMA)
MA9labelXPos = bar_index + math.round(ta.change(bar_index)*distance9)
MA9Price = show_ma_prices9 ? " - "+str.tostring(math.round_to_mintick(ma9)) : ""
ma9LabelText = MAtimeframe9Text == "" ? labelPadding100_200+ma9Formula+" "+str.tostring(ma9Length)+MA9Price : labelPadding100_200+ma9Formula+" "+str.tostring(ma9Length)+" ("+MAtimeframe9Text+")"+MA9Price
var string maGroup13 = '----------------------------Moving Average 13----------------------------'
enableMA13 = input.bool(true, "Enable MA", group=maGroup13)
enableMA13Label = input.bool(true, "Enable MA label", group=maGroup13)
show_ma_prices13 = input.bool(true, "Enable price", group=maGroup13)
ma13Formula = input.string("", options=['', 'HMA', 'SMA','SWMA','RMA','VWAP','VWMA','WMA', 'ZLEMA', 'DEMA', 'TEMA', 'ALMA', 'ZLSMA'], title="Formula", group=maGroup13)
ma13Length = input.int(13,"Length", group=maGroup13)
distance13 = input.int(0, "MA offset", group=maGroup13)
ma13Color = input.color(color.rgb(150, 155, 148, 16), "Color", group=maGroup13)
ma13Text = str.tostring(ma13Formula) + ' ' + str.tostring(ma13Length)
ma13 = _get(resInputMA, ma(ma13Formula, close, ma13Length))
ma13p = plot(ma13, color=ma13Color, title="13) EMA 13", display=display.none)
showMA13 = enableMA13 ? display.all : display.none
MAtimeframe13Text = get_timeframe_title(resInputMA)
MA13labelXPos = bar_index + math.round(ta.change(bar_index)*distance13)
MA13Price = show_ma_prices13 ? " - "+str.tostring(math.round_to_mintick(ma13)) : ""
ma13LabelText = MAtimeframe13Text == "" ? labelPadding13_48+ma13Formula+" "+str.tostring(ma13Length)+MA13Price : labelPadding13_48+ma13Formula+" "+str.tostring(ma13Length)+" ("+MAtimeframe13Text+")"+MA13Price
var string maGroup14 = '----------------------------Moving Average 14----------------------------'
enableMA14 = input.bool(true, "Enable MA", group=maGroup14)
enableMA14Label = input.bool(true, "Enable MA label", group=maGroup14)
show_ma_prices14 = input.bool(true, "Enable price", group=maGroup14)
ma14Formula = input.string("", options=['', 'HMA', 'SMA','SWMA','RMA','VWAP','VWMA','WMA', 'ZLEMA', 'DEMA', 'TEMA', 'ALMA', 'ZLSMA'], title="Formula", group=maGroup14)
ma14Length = input.int(48,"Length", group=maGroup14)
distance14 = input.int(0, "MA offset", group=maGroup14)
ma14Color = input.color(color.rgb(219, 96, 219, 14), "Color", group=maGroup14)
ma14Text = str.tostring(ma14Formula) + ' ' + str.tostring(ma14Length)
ma14 = _get(resInputMA, ma(ma14Formula, close, ma14Length))
ma14p = plot(ma14, color=ma14Color, title="14) EMA 48", display=display.none)
showMA14 = enableMA14 ? display.all : display.none
MAtimeframe14Text = get_timeframe_title(resInputMA)
MA14labelXPos = bar_index + math.round(ta.change(bar_index)*distance14)
MA14Price = show_ma_prices14 ? " - "+str.tostring(math.round_to_mintick(ma14)) : ""
ma14LabelText = MAtimeframe14Text == "" ? labelPadding13_48+ma14Formula+" "+str.tostring(ma14Length)+MA14Price : labelPadding13_48+ma14Formula+" "+str.tostring(ma14Length)+" ("+MAtimeframe14Text+")"+MA14Price
// 🟦🟦🟦 SimpleCryptoLife version of label input code
labelSizeInput = input.string(title="$/% Label Size-right of candle", options=["Tiny", "Small", "Normal", "Large", "Huge"], defval="Large", group="-----------------------------Current price/% 1----------------------------")
labelSizeInput2 = input.string(title="$/% Label Size-above candle", options=["Tiny", "Small", "Normal", "Large", "Huge"], defval="Normal", group="-----------------------------Current price/% 1----------------------------")
labelSizeInput1 = input.string(title="% Offset Label Size", options=["Tiny", "Small", "Normal", "Large", "Huge"], defval="Normal", group="-----------------------------Current price/% 1----------------------------")
f_labelSizeFromInput(_input) =>
_size = switch _input
"Tiny" => size.tiny
"Small" => size.small
"Normal" => size.normal
"Large" => size.large
"Huge" => size.huge
=> size.normal // Default if the other conditions aren't met
labelSize = f_labelSizeFromInput(labelSizeInput)
labelSize2 = f_labelSizeFromInput(labelSizeInput2)
labelSize1 = f_labelSizeFromInput(labelSizeInput1)
// Code related to real price.
regularCandles = ticker.new(syminfo.prefix, syminfo.ticker)
[o,h,l,c] = request.security(regularCandles, timeframe.period, [open,high,low,close])
settlementClose = request.security(regularCandles, "D", close, barmerge.gaps_off, barmerge.lookahead_on)
evenClose = request.security(regularCandles, "60", close, barmerge.gaps_off, barmerge.lookahead_on)
lines = line.all
enableRealClose = input.bool(true, "Current $/% - (right of candle)", group="-----------------------------Current price/% 1----------------------------")
realPriceDistance = input.int(0, "$/% offset - (right of candle)", group="-----------------------------Current price/% 1----------------------------")
plotMarketChangeLabel = input.bool(false, "Current $/% (above candle)", group="-----------------------------Current price/% 1----------------------------")
//realPriceDistance1 = input.int(6, "$/% offset - (above candle)", group="-----------------------------Current price/% 1----------------------------")
plotLevelChange = input.string("Settlement", "Measure change from:", options=['Open', 'Close', 'Settlement'], group="-----------------------------Current price/% 1----------------------------")
enableRealClose0 = input.bool(false, "Current $ - yellow", group="-----------------------------Current price/% 1----------------------------")
enableRealClose01 = input.bool(false, "Current $ - R/G", group="-----------------------------Current price/% 1----------------------------")
enableRealClose02 = input.bool(false, "$ line - 50", group="-----------------------------Current price/% 1----------------------------")
enableRealClose022 = input.bool(false, "$ line - 50", group="-----------------------------Current price/% 1----------------------------")
enableRealClose03 = input.bool(false, "$ line - 50-R/G", group="-----------------------------Current price/% 1----------------------------")
enableRealClose033 = input.bool(false, "$ line - 50-R/G", group="-----------------------------Current price/% 1----------------------------")
enableRealClose0333 = input.bool(false, "$ line - 75", group="-----------------------------Current price/% 1----------------------------")
enableRealClose03333 = input.bool(false, "$ line - 75", group="-----------------------------Current price/% 1----------------------------")
enableRealClose033333 = input.bool(false, "$ line - 75-R/G", group="-----------------------------Current price/% 1----------------------------")
enableRealClose0333333 = input.bool(false, "$ line - 75-R/G", group="-----------------------------Current price/% 1----------------------------")
enableRealClose04 = input.bool(false, "$ line - 100", group="-----------------------------Current price/% 1----------------------------")
enableRealClose044 = input.bool(false, "$ line - 100", group="-----------------------------Current price/% 1----------------------------")
enableRealClose05 = input.bool(false, "$ line - 100-R/G", group="-----------------------------Current price/% 1----------------------------")
enableRealClose055 = input.bool(false, "$ line - 100-R/G", group="-----------------------------Current price/% 1----------------------------")
enableRealClose06 = input.bool(false, "$ line - 200", group="-----------------------------Current price/% 1----------------------------")
enableRealClose07 = input.bool(false, "$ line - 200-R/G", group="-----------------------------Current price/% 1----------------------------")
enableRealClose09 = input.bool(true, "$ line - 500-R/G", group="-----------------------------Current price/% 1----------------------------")
enableRealClose11 = input.bool(true, "$ line - 500-R/G", group="-----------------------------Current price/% 1----------------------------")
enableRealClose10 = input.bool(false, "$ line - 500", group="-----------------------------Current price/% 1----------------------------")
enableRealClose08 = input.bool(false, "$ line - 500", group="-----------------------------Current price/% 1----------------------------")
enablePercentage_Above = input.bool(false, "% above current price", group="-----------------------------Current price/% 1----------------------------")
enablePercentage_Below = input.bool(false, "% below current price", group="-----------------------------Current price/% 1----------------------------")
percentage = input.float(2, "% from current $", group="-----------------------------Current price/% 1----------------------------")
PercentageDistance = input.int(0, "% offset", group="-----------------------------Current price/% 1----------------------------")
//in_atrMultiplier = input.float(title="Spacing as a multiple of ATR", defval=2.0, step=0.5, minval=0.1, maxval=10.0, tooltip="How far above/below the close should the % labels appear? This value is a multiplier of the Average True Range.") // 🟦🟦🟦
enableRealCloseOnPriceScale = input.bool(true, "Show on price scale", group="-----------------------------Current price/% 1----------------------------")
percentageAboveLevel = math.round_to_mintick(c*(1+percentage/100))
percentageBelowLevel = math.round_to_mintick(c/(1+percentage/100))
percentageAboveLabelText = LabelPadding_Above_Below + str.tostring(percentageAboveLevel) + "\n " + LabelPadding_Above_Below + "-" + str.tostring(percentage) + "%- "
percentageBelowLabelText = LabelPadding_Above_Below + str.tostring(percentageBelowLevel) + "\n " + LabelPadding_Above_Below + "-" + str.tostring(percentage) + "%- "
var marketOpen = 0.0
var marketClose = 0.0
var settlementPrice = 0.0
if session.isfirstbar
marketOpen := o
marketClose := c[1]
settlementPrice := session.ismarket ? settlementClose[1] : settlementClose
if barstate.islast
settlementPrice := c
// if not(timeframe.isintraday)
// settlementPrice := c[1]
//if session.isfirstbar and bar_index == last_bar_index and not(timeframe.isintraday)
// settlementPrice := settlementClose
//plot(marketOpen, color=color.fuchsia, style=plot.style_stepline, display=plotOpen ? display.all : display.none)
//plot(marketClose, color=color.lime, style=plot.style_stepline, display=plotClose ? display.all : display.none)
openLevel = nz(marketOpen)
closeLevel = nz(marketClose)
settlementLevel = nz(settlementPrice)
float rsiChart = ta.rsi(close,14) // 🟦🟦🟦 You can search and replace rsiEMATF with rsiChart if you want to simply use the "normal" RSI
// float rsiEMATF = request.security(syminfo.tickerid, resInputMA, ta.rsi(close,14), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off) // The RSI based on the EMA timeframe. This uses the current returned value. This is ok for just showing current RSI but would cause problems if used historically.
f_CMO(_CMO_length, _RSI_length) =>
float _momm = ta.change(close)
float _m1 = _momm >= 0.0 ? _momm : 0.0
float _m2 = _momm >= 0.0 ? 0.0 : -_momm
float _sm1 = math.sum(_m1, _CMO_length)
float _sm2 = math.sum(_m2, _CMO_length)
float _nom = _sm1-_sm2
float _div = _sm1+_sm2
float _chandeMO = math.round(100 * _nom / _div,2)
float _RSI = ta.rsi(close,_RSI_length)
[_chandeMO, _RSI]
// [chandeMO, rsiEMATF] = f_CMO(_CMO_length=in_CMO_length, _RSI_length=in_RSI_length)
[chandeMO, rsiEMATF] = request.security(syminfo.tickerid, resInputMA, f_CMO(_CMO_length=in_CMO_length, _RSI_length=in_RSI_length), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off)
changeLevel = plotLevelChange == "Open" ? openLevel : plotLevelChange == "Close" ? closeLevel : settlementLevel
changePrice = ((math.round_to_mintick(evenClose)/changeLevel)*100)-100
changeSinceLevel = str.tostring(changePrice, format=format.percent)
// 🟦🟦🟦 Display buy-sell volume, formatted nicely
type OHLCVol // Create User-Defined Type composed of volume + OHLC
float volume = volume
float open = open
float high = high
float low = low
float close = close
f_OHLCVol_chart() => OHLCVol.new() // Create a new object of type OHLCVol by calling a function. This way it's more efficient to get it from security()
OHLCVol_sec_daily = request.security(syminfo.tickerid, in_volumeTF_daily, f_OHLCVol_chart(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off) // Get volume, OHLC all at once from the daily timeframe
var float dailyVolume_daily = na
var float dailyClose_daily = na
var float dailyHigh_daily = na
var float dailyOpen_daily = na
var float dailyLow_daily = na
if barstate.islast
dailyVolume_daily := OHLCVol_sec_daily.volume
dailyOpen_daily := OHLCVol_sec_daily.open
dailyHigh_daily := OHLCVol_sec_daily.high
dailyLow_daily := OHLCVol_sec_daily.low
dailyClose_daily := OHLCVol_sec_daily.close
float dailyBuyVolume_daily = dailyHigh_daily == dailyLow_daily ? 0 : nz(dailyVolume_daily) * (dailyClose_daily - dailyLow_daily) / (dailyHigh_daily - dailyLow_daily)
float dailySellVolume_daily = dailyHigh_daily==dailyLow_daily ? 0 : nz(dailyVolume_daily) * (dailyHigh_daily - dailyClose_daily) / (dailyHigh_daily - dailyLow_daily)
float dailyBuyVolumePercent_daily = dailyBuyVolume_daily / dailyVolume_daily * 100
float dailySellVolumePercent_daily = dailySellVolume_daily / dailyVolume_daily * 100
f_formatNumberWithCommas(float _number) =>
string _numberAsCurrency = str.format("{0, number, currency}", math.round(_number,0))
string _numberWithCommas = str.replace(_numberAsCurrency, "$", "")
string _numberWithoutTrailingZeroes = str.replace(_numberWithCommas, ".00", "")
f_formatNumberWithLetters(float _number) =>
float _roundNumber = math.round(_number,0)
string _formattedNumber = na
float _dividedNumber = na
if _roundNumber > 1000 and _roundNumber < 1000000
_dividedNumber := _roundNumber/1000
_formattedNumber := str.tostring(_dividedNumber) + "k"
else if _roundNumber > 1000000 and _roundNumber < 1000000000
_dividedNumber := _roundNumber/1000000
_formattedNumber := str.tostring(_dividedNumber) + "m"
else if _roundNumber > 1000000000
_dividedNumber := _roundNumber/1000000000
_formattedNumber := str.tostring(_dividedNumber) + "b"
else
_formattedNumber := str.tostring(_roundNumber)
_formattedNumber
string dailyVolumeString_daily = f_formatNumberWithCommas(_number=dailyVolume_daily) + " " + "(" + str.tostring(value=dailyBuyVolumePercent_daily, format='#') + "/" + str.tostring(value=dailySellVolumePercent_daily, format='#') + ")"
// debugLabel = label.new(bar_index,close, style = label.style_label_left, text=debugText, textcolor=color.white, color=color.black, size=size.normal)
// label.delete(debugLabel[1])
float priceChangeAmount = c-changeLevel // 🟦🟦🟦
// New section to make the text lines a bit more organised
string text_CMO_RSI = str.tostring(chandeMO) + " * " + str.tostring(math.round(rsiEMATF,2))
string strike = "\n" + labelPadding + "⚡" + "\n"
string strike1 = "\n" + labelPadding_volume + "⚡" + "\n"
string text_volume_daily = labelPadding + dailyVolumeString_daily + " d"
string text_above_percentage = str.tostring(percentage) + "% " + "(" + str.tostring(percentageAboveLevel) + ")"
string text_below_percentage = "-" + str.tostring(percentage) + "% " + "(" + str.tostring(percentageBelowLevel) + ")"
string text_priceChange = labelPadding + str.tostring(c) + " (" + str.tostring(priceChangeAmount) + " (" + changeSinceLevel + "))"
// This is the "main" bit, which is enabled by the enableRealClose option // 🟦🟦🟦
string closeLabelText = text_volume_daily + strike + labelPadding + text_CMO_RSI + strike + labelPadding + text_above_percentage + strike + labelPadding + text_below_percentage + strike + text_priceChange
//string closeLabelText_volumeprofiles = text_volume + strike1 + text_volume_10m + strike1 + text_volume_30m + strike1 + text_volume_1h + strike1 + text_volume_4h + strike1 + text_volume_daily
////below script manipulates yellow and R/G price change, RSI and percentage below value
string extraLabelText = text_CMO_RSI + strike + labelPadding + text_above_percentage + strike + labelPadding + text_below_percentage + strike // This is the one that gets shown or hidden by the input enableRealClose0 // 🟦🟦🟦
//below manipulates yellow but not R/G
string text_price = labelPadding + str.tostring(c) + " * " + str.tostring(priceChangeAmount)
closeLabelText1 = extraLabelText + text_price
//if barstate.islast and plotMarketChangeLabel
//label.new(bar_index,close,yloc=c > changeLevel ? yloc.abovebar : yloc.abovebar, style = c > changeLevel ? label.style_label_up : label.style_label_up, text=marketOpenLabelText1, textcolor=percLabelColor1, color=percLabelColor, size=labelSize)
//below manipulates current price R/G but not yellow
closeLabelText2 = extraLabelText + labelPadding + str.tostring(c) + " * " + str.tostring(priceChangeAmount) // 🟦🟦🟦
marketOpenLabelText = str.tostring(c) + "\n" + changeSinceLevel
marketOpenLabelText1 = str.tostring(c) + "\n"
//marketOpenLabelText2 = str.tostring(c) + "\n"
plot(c, display=enableRealCloseOnPriceScale ? display.price_scale : display.none)
percLabelColor = c > changeLevel ? color.rgb(0, 0, 0, 100) : color.rgb(0, 0, 0, 100)
percLabelColor1 = c > changeLevel ? color.green : color.rgb(247, 21, 21)
percLabelColor2 = c > changeLevel ? color.white : color.white
percLabelColor3 = c > changeLevel ? color.rgb(255, 235, 59, 25) : color.rgb(255, 235, 59, 25)
var label marketChangeLabel = na
if barstate.islast and plotMarketChangeLabel
marketChangeLabel := label.new(bar_index,close,yloc=c > changeLevel ? yloc.abovebar : yloc.abovebar, style = c > changeLevel ? label.style_label_up : label.style_label_up, text=marketOpenLabelText, textcolor=percLabelColor1, color=percLabelColor, size=labelSize2)
label.delete(marketChangeLabel[1])
var label marketChangeLabel2 = na
if barstate.islast and plotMarketChangeLabel
marketChangeLabel2 := label.new(bar_index,close,yloc=c > changeLevel ? yloc.abovebar : yloc.abovebar, style = c > changeLevel ? label.style_label_up : label.style_label_up, text=marketOpenLabelText1, textcolor=percLabelColor1, color=percLabelColor, size=labelSize2)
label.delete(marketChangeLabel2[1])
// ------ PRICE LABELS -------
labelXPosAboveBelow = bar_index + math.round(ta.change(bar_index)*PercentageDistance)
labelXPosRealClose = bar_index + math.round(ta.change(bar_index)*realPriceDistance)
priceStringCurrent = str.tostring(c)
priceStringCurrentPerc = changeSinceLevel
styleline = line.new(bar_index, c, bar_index+0, c, color=color.white)
//styleline2 = line.new(bar_index, c, bar_index+0, c, color=color.white)
//styleline3 = line.new(bar_index, c, bar_index+0, c, color=color.white)
line.set_style(styleline, style=line.style_dotted)
//line.set_style(styleline2, style=line.style_arrow_both)
//line.set_style(styleline3, style=line.style_arrow_left)
// 🟦🟦🟦 Changed the vertical spacing to ATR-based
//float atrAbove = c+(ta.atr(14)*in_atrMultiplier)
//float atrBelow = c-(ta.atr(14)*in_atrMultiplier)
if barstate.islast
// Uncomment these lines if you move this part to a separate indicator
// if array.size(labels) > 0
// for i = 0 to array.size(labels) - 1
// oldLabel = array.get(labels, i)
// label.delete(oldLabel)
if array.size(lines) > 0
for i = 0 to array.size(lines) - 1
oldLine = array.get(lines, i)
line.delete(oldLine)
// and then create new ones
var label ma7Label = na
var label ma9Label = na
var label ma13Label = na
var label ma14Label = na
var label labelRealClose = na
var label labelRealClose_volume = na
var label labelRealClose0 = na
var label labelRealClose01 = na
var label labelRealClose5 = na
var label labelRealClose6 = na
var label labelRealClose7 = na
var label labelRealClose8 = na
var label percentageAboveLabel = na
var label percentageBelowLabel = na
var label text_above_percentage_label = na
var label text_below_percentage_label = na
//if plotMarketChangeLabel //follow price and % above candle
//line.new(bar_index, c, bar_index+0, c, color=color.white, style=line.style_dotted)
//regularCloseLabel = label.new(bar_index+realPriceDistance, c, closeLabelText, yloc=yloc.price, style=label.style_none, textcolor=percLabelColor1, textalign = text.align_left)
//marketChangeLabel2 := label.new(labelXPosRealClose, c, text = closeLabelText, xloc=xloc.bar_index, color = percLabelColor1, textcolor = percLabelColor1, style = label.style_none, size=labelSize)
//label.delete(marketChangeLabel2[1])
if enableMA7 and enableMA7Label
ma7Label := label.new(MA7labelXPos, ma7, ma7LabelText, xloc=xloc.bar_index, style=label.style_label_center, color=color.rgb(0, 0, 0, 100), textcolor = ma7Color)
label.delete(ma7Label[1])
if enableMA9 and enableMA9Label
ma9Label := label.new(MA9labelXPos, ma9, ma9LabelText, xloc=xloc.bar_index, style=label.style_label_center, color=color.rgb(0, 0, 0, 100), textcolor = ma9Color)
label.delete(ma9Label[1])
if enableMA13 and enableMA13Label
ma13Label := label.new(MA13labelXPos, ma13, ma13LabelText, xloc=xloc.bar_index, style=label.style_label_center, color=color.rgb(0, 0, 0, 100), textcolor = ma13Color)
label.delete(ma13Label[1])
if enableMA14 and enableMA14Label
ma14Label := label.new(MA14labelXPos, ma14, ma14LabelText, xloc=xloc.bar_index, style=label.style_label_center, color=color.rgb(0, 0, 0, 100), textcolor = ma14Color)
label.delete(ma14Label[1])
if enableRealClose //follow price and %
line.new(bar_index, c, bar_index+0, c, color=color.white, style=line.style_dotted)
//regularCloseLabel = label.new(bar_index+realPriceDistance, c, closeLabelText, yloc=yloc.price, style=label.style_none, textcolor=percLabelColor1, textalign = text.align_left)
labelRealClose := label.new(labelXPosRealClose, c, text = closeLabelText, xloc=xloc.bar_index, color = percLabelColor1, textcolor = percLabelColor1, style = label.style_none, size=labelSize)
label.delete(labelRealClose[1])
//if enableRealClose_volumeprofiles //follow price and %
//line.new(bar_index, c, bar_index+0, c, color=color.white, style=line.style_dotted)
//regularCloseLabel = label.new(bar_index+realPriceDistance, c, closeLabelText, yloc=yloc.price, style=label.style_none, textcolor=percLabelColor1, textalign = text.align_left)
//labelRealClose_volume := label.new(labelXPosRealClose, c, text = closeLabelText_volumeprofiles, xloc=xloc.bar_index, color = percLabelColor1, textcolor = percLabelColor1, style = label.style_none, size=labelSize)
//label.delete(labelRealClose_volume[1])
if enableRealClose0 //follow price and %
line.new(bar_index, c, bar_index+0, c, color=color.rgb(255, 235, 59, 25), style=line.style_dotted)
//regularCloseLabel = label.new(bar_index+realPriceDistance, c, closeLabelText1, yloc=yloc.price, style=label.style_none, textcolor=percLabelColor2, textalign = text.align_left)
labelRealClose0 := label.new(labelXPosRealClose, c, text = labelPadding+closeLabelText1, xloc=xloc.bar_index, color = percLabelColor3, textcolor = percLabelColor3, style = label.style_none, size=labelSize)
label.delete(labelRealClose0[1])
if enableRealClose01 //follow price and %
line.new(bar_index, c, bar_index+0, c, color=color.white, style=line.style_dotted)
//regularCloseLabel = label.new(bar_index+realPriceDistance, c, closeLabelText2, yloc=yloc.price, style=label.style_none, textcolor=percLabelColor1, textalign = text.align_left)
labelRealClose01 := label.new(labelXPosRealClose, c, text = labelPadding+closeLabelText2, xloc=xloc.bar_index, color = percLabelColor1, textcolor = percLabelColor1, style = label.style_none, size=labelSize)
label.delete(labelRealClose01[1])
if enableRealClose02 //yellow line length 50
line.new(bar_index, c, bar_index+50, c, color=color.rgb(255, 235, 59), style=line.style_dotted)
//regularCloseLabel1 = label.new(bar_index+realPriceDistance, c, yloc=yloc.price, style=label.style_none, textcolor=percLabelColor, textalign = text.align_left)
if enableRealClose022 //yellow line length 50
line.new(bar_index, c, bar_index+50, c, color=color.rgb(255, 235, 59), style=line.style_dotted)
//regularCloseLabel1 = label.new(bar_index+realPriceDistance, c, yloc=yloc.price, style=label.style_none, textcolor=percLabelColor3, textalign = text.align_left)
if enableRealClose03 //red green option length 50
line.new(bar_index, c, bar_index+50, c, color=percLabelColor1, style=line.style_dotted)
//regularCloseLabel1 = label.new(bar_index+realPriceDistance, c, yloc=yloc.price, style=label.style_none, textcolor=percLabelColor1, color=percLabelColor, textalign = text.align_left)
if enableRealClose033 //red green option length 50
line.new(bar_index, c, bar_index+50, c, color=percLabelColor1, style=line.style_dotted)
//regularCloseLabel1 = label.new(bar_index+realPriceDistance, c, yloc=yloc.price, style=label.style_none, textcolor=percLabelColor1, color=percLabelColor, textalign = text.align_left)
if enableRealClose0333 //length 75 white line
line.new(bar_index, c, bar_index+75, c, color=color.rgb(255, 235, 59), style=line.style_dotted)
//regularCloseLabel1 = label.new(bar_index+realPriceDistance, c, yloc=yloc.price, style=label.style_none, textcolor=percLabelColor1, color=percLabelColor, textalign = text.align_left)
if enableRealClose03333 //length 75 white line
line.new(bar_index, c, bar_index+75, c, color=color.yellow, style=line.style_dotted)
//regularCloseLabel1 = label.new(bar_index+realPriceDistance, c, yloc=yloc.price, style=label.style_none, textcolor=percLabelColor1, color=percLabelColor, textalign = text.align_left)
if enableRealClose033333 //red green option length 75
line.new(bar_index, c, bar_index+75, c, color=percLabelColor1, style=line.style_dotted)
//regularCloseLabel1 = label.new(bar_index+realPriceDistance, c, yloc=yloc.price, style=label.style_none, textcolor=percLabelColor1, color=percLabelColor, textalign = text.align_left)
if enableRealClose0333333 //red green option length 75
line.new(bar_index, c, bar_index+75, c, color=percLabelColor1, style=line.style_dotted)
//regularCloseLabel1 = label.new(bar_index+realPriceDistance, c, yloc=yloc.price, style=label.style_none, textcolor=percLabelColor1, color=percLabelColor, textalign = text.align_left)
if enableRealClose04 //white line length 100
line.new(bar_index, c, bar_index+100, c, color=color.yellow, style=line.style_dotted)
//regularCloseLabel1 = label.new(bar_index+realPriceDistance, c, yloc=yloc.price, style=label.style_none, textcolor=percLabelColor, textalign = text.align_left)
if enableRealClose044 //white line length 100
line.new(bar_index, c, bar_index+100, c, color=color.yellow, style=line.style_dotted)
//regularCloseLabel1 = label.new(bar_index+realPriceDistance, c, yloc=yloc.price, style=label.style_none, textcolor=percLabelColor, textalign = text.align_left)
if enableRealClose05 //red green option length 100
line.new(bar_index, c, bar_index+100, c, color=percLabelColor1, style=line.style_dotted)
//regularCloseLabel1 = label.new(bar_index+realPriceDistance, c, yloc=yloc.price, style=label.style_none, textcolor=percLabelColor1, color=percLabelColor, textalign = text.align_left)
if enableRealClose055 //red green option length 100
line.new(bar_index, c, bar_index+100, c, color=percLabelColor1, style=line.style_dotted)
//regularCloseLabel1 = label.new(bar_index+realPriceDistance, c, yloc=yloc.price, style=label.style_none, textcolor=percLabelColor1, color=percLabelColor, textalign = text.align_left)
if enableRealClose06 //white line length 200
line.new(bar_index, c, bar_index+200, c, color=color.yellow, style=line.style_dotted)
//regularCloseLabel1 = label.new(bar_index+realPriceDistance, c, yloc=yloc.price, style=label.style_none, textcolor=percLabelColor, textalign = text.align_left)
if enableRealClose07 //red green option length 200
line.new(bar_index, c, bar_index+200, c, color=percLabelColor1, style=line.style_dotted)
//regularCloseLabel1 = label.new(bar_index+realPriceDistance, c, yloc=yloc.price, style=label.style_none, textcolor=percLabelColor1, color=percLabelColor, textalign = text.align_left)
if enableRealClose08 //white line length 500
line.new(bar_index, c, bar_index+500, c, color=color.yellow, style=line.style_dotted)
//regularCloseLabel1 = label.new(bar_index+realPriceDistance, c, yloc=yloc.price, style=label.style_none, textcolor=percLabelColor, textalign = text.align_left)
if enableRealClose09 //red green option length 500
line.new(bar_index, c, bar_index+500, c, color=percLabelColor1, style=line.style_dotted)
//regularCloseLabel1 = label.new(bar_index+realPriceDistance, c, yloc=yloc.price, style=label.style_none, textcolor=percLabelColor1, color=percLabelColor, textalign = text.align_left)
if enableRealClose10 //white line length 500 - to highlight line
line.new(bar_index, c, bar_index+500, c, color=color.yellow, style=line.style_dotted)
//regularCloseLabel1 = label.new(bar_index+realPriceDistance, c, yloc=yloc.price, style=label.style_none, textcolor=percLabelColor, textalign = text.align_left)
if enableRealClose11 //red green option length 500 - to highlight line
line.new(bar_index, c, bar_index+500, c, color=percLabelColor1, style=line.style_dotted)
//regularCloseLabel1 = label.new(bar_index+realPriceDistance, c, yloc=yloc.price, style=label.style_none, textcolor=percLabelColor1, color=percLabelColor, textalign = text.align_left)
var string arrowGroup = '----------------------------Conviction Arrows----------------------------'
//arrowsResInput = input.timeframe(title='Timeframe', defval='', group=arrowGroup)
//resInputMA1 = input.timeframe(title='Conviction Arrows TF', defval='', group=maGroup0)
show_conviction_arrows = input.bool(true, 'Enable Conviction Arrows', group=arrowGroup)
fast_conviction_ema = input.int(13, 'Fast Conviction EMA Length', group=arrowGroup)
slow_conviction_ema = input.int(48, 'Slow Conviction EMA Length', group=arrowGroup)
fast_conviction_ema1 = input.int(100, 'Fast Conviction EMA Length', group=arrowGroup)
slow_conviction_ema1 = input.int(200, 'Slow Conviction EMA Length', group=arrowGroup)
bullish_conviction_color_13_48 = input.color(color.rgb(167, 180, 180, 16), 'Bullish Conviction 13/48 Color', group=arrowGroup)
bearish_conviction_color_13_48 = input.color(color.rgb(179, 93, 153), 'Bearish Conviction 13/48 Color', group=arrowGroup)
bullish_conviction_color_100_200 = input.color(color.rgb(120, 216, 82, 16), 'Bullish 100/200 Arrow Color', group=arrowGroup)
bearish_conviction_color_100_200 = input.color(color.rgb(160, 52, 52), 'Bearish 100/200 Arrow Color', group=arrowGroup)
fast_conviction_ema_value = _get2(resInputMA1, ta.ema(close, fast_conviction_ema))
slow_conviction_ema_value = _get2(resInputMA1, ta.ema(close, slow_conviction_ema))
fast_conviction_ema_value1 = _get3(resInputMA1, ta.ema(close, fast_conviction_ema1))
slow_conviction_ema_value1 = _get3(resInputMA1, ta.ema(close, slow_conviction_ema1))
// Conviction Arrows (default based on 13/48)
bullish_conviction = fast_conviction_ema_value >= slow_conviction_ema_value
bearish_conviction = fast_conviction_ema_value < slow_conviction_ema_value
bullish_conviction_confirmed = bullish_conviction[0] == true and bullish_conviction[1] == false
bearish_conviction_confirmed = bearish_conviction[0] == true and bearish_conviction[1] == false
plotshape(bullish_conviction_confirmed and show_conviction_arrows, color=bullish_conviction_color_13_48, location=location.top, size=size.tiny, title='13/48 top', text='13/48', textcolor=color.rgb(189, 190, 194), display=display.none)
plotshape(bullish_conviction_confirmed and show_conviction_arrows, style=shape.triangleup, color=bullish_conviction_color_13_48, location=location.belowbar, size=size.tiny, title='13/48 bull arrow up', textcolor=color.rgb(189, 190, 194), display=display.none)
plotshape(bearish_conviction_confirmed and show_conviction_arrows, color=bearish_conviction_color_13_48, location=location.top, size=size.tiny, title='48/13 top', text='48/13', textcolor=color.purple, display=display.none)
plotshape(bearish_conviction_confirmed and show_conviction_arrows, style=shape.triangledown, color=bearish_conviction_color_13_48, location=location.abovebar, size=size.tiny, title='48/13 bear arrow down', textcolor=color.purple, display=display.none)
// Conviction Arrows (default based on 100/200)
bullish_conviction1 = fast_conviction_ema_value1 >= slow_conviction_ema_value1
bearish_conviction1 = fast_conviction_ema_value1 < slow_conviction_ema_value1
bullish_conviction_confirmed1 = bullish_conviction1[0] == true and bullish_conviction1[1] == false
bearish_conviction_confirmed1 = bearish_conviction1[0] == true and bearish_conviction1[1] == false
plotshape(bullish_conviction_confirmed1 and show_conviction_arrows, color=bullish_conviction_color_100_200, location=location.top, size=size.small, title='100/200 top', text='100/200', textcolor=color.rgb(120, 216, 82, 16), display=display.none)
plotshape(bullish_conviction_confirmed1 and show_conviction_arrows, style=shape.triangleup, color=bullish_conviction_color_100_200, location=location.belowbar, size=size.small, title='100/200 bull arrow up', textcolor=color.rgb(120, 216, 82, 16), display=display.none)
plotshape(bearish_conviction_confirmed1 and show_conviction_arrows, color=bearish_conviction_color_100_200, location=location.top, size=size.small, title='200/100 top', text='200/100', textcolor=color.rgb(221, 73, 73, 75), display=display.none)
plotshape(bearish_conviction_confirmed1 and show_conviction_arrows, style=shape.triangledown, color=bearish_conviction_color_100_200, location=location.abovebar, size=size.small, title='200/100 bear arrow down', textcolor=color.rgb(221, 73, 73, 75), display=display.none)
// Everything inside this is done only when last bar is loaded, no point in writing and deleting
// labels for the whole history
ma1(formula, source, length) =>
switch formula
"EMA" => ta.ema(source, length)
// Input options
//EMA_13 = input.int(title="EMA 1", defval=13)
//EMA_48 = input.int(title="EMA 2", defval=48)
//EMA_100 = input.int(title="EMA 3", defval=100)
//EMA_200 = input.int(title="EMA 4", defval=200)
// Calculate values
Alert_EMA_13 = ta.ema(close, ma13Length)
Alert_EMA_48 = ta.ema(close, ma14Length)
Alert_EMA_100 = ta.ema(close, ma7Length)
Alert_EMA_200 = ta.ema(close, ma9Length)
// Create Buy/Sell Arrows
//plotshape(Buy, color=green, style=shape.arrowup, text="Buy", location=location.bottom)
//plotshape(Sell, color=red, style=shape.arrowdown, text="Sell", location=location.top)
// Show on Chart
//plot(Alert_EMA_13, color=color.rgb(150, 155, 148, 16), title="EMA 13", display=display.none)
//plot(Alert_EMA_48, color=color.rgb(219, 96, 219, 14), title="EMA 48", display=display.none)
//plot(Alert_EMA_100, color=color.rgb(120, 216, 82, 16), title="EMA 100", display=display.none)
//plot(Alert_EMA_200, color=color.rgb(221, 73, 73), title="EMA 200", display=display.none)
// Create alert conditions
//alertcondition(condition=crossover(Alert_EMA_13, Alert_EMA_48),
//title="EMA 21 Cross Above",
//message="EMA 21 crossed over EMA 55."
//)
//alertcondition(condition=crossunder(Alert_EMA_13, Alert_EMA_48),
//title="EMA 13 Cross Above",
//message="EMA 13 crossed over EMA 48."
//)
// 13/48
TrendingUp1() => Alert_EMA_13 > Alert_EMA_48
TrendingDown2() => Alert_EMA_13 < Alert_EMA_48
//barcolor(TrendingUp() ? color.green : TrendingDown() ? color.red : color.blue)
// EMA cross background color alert to chart (Tall Candle)
Uptrend1() => TrendingUp1() and TrendingDown2()[1]
Downtrend1() => TrendingDown2() and TrendingUp1()[1]
bgcolor(Uptrend1() ? color.rgb(173, 173, 173, 70) : Downtrend1() ? color.rgb(211, 121, 211, 70) : na, title="13/48 crossover")
// 100/200
TrendingUp3() => Alert_EMA_100 > Alert_EMA_200
TrendingDown4() => Alert_EMA_100 < Alert_EMA_200
//barcolor(TrendingUp() ? color.green : TrendingDown() ? color.red : color.blue)
// EMA cross background color alert to chart (Tall Candle)
Uptrend2() => TrendingUp3() and TrendingDown4()[1]
Downtrend2() => TrendingDown4() and TrendingUp3()[1]
bgcolor(Uptrend2() ? color.rgb(113, 224, 113, 70) : Downtrend2() ? color.rgb(221, 73, 73, 70) : na, title="100/200 crossover")
//13/48
//Buy = Uptrend1() and close > close[1]
//Sell = Downtrend1() and close < close[1]
//plotshape(Buy, color=color.gray, style=shape.triangleup, text="13/48", location=location.top, textcolor=color.rgb(173, 173, 173))
//plotshape(Sell, color=color.purple, style=shape.triangledown, text="13/48", location=location.top, textcolor=color.rgb(211, 121, 211))
//100/200
//Buy_1 = Uptrend2() and close > close[1]
//Sell_1 = Downtrend2() and close < close[1]
//plotshape(Buy_1, color=color.green, style=shape.triangleup, text="100/200", location=location.top, textcolor=color.rgb(113, 224, 113, 3))
//plotshape(Sell_1, color=color.red, style=shape.triangledown, text="100/200", location=location.top, textcolor= color.rgb(243, 95, 95)) |
Rekt Edge Reversion Band | https://www.tradingview.com/script/Oc9qS4SN-Rekt-Edge-Reversion-Band/ | RektCapDao | https://www.tradingview.com/u/RektCapDao/ | 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/
// last edited: 2023-03-03 11:30AM v. 28.0
// © RektEdge
//@version=5
import maartenheremans/statistics/1 as stats
import ZenAndTheArtOfTrading/ZenLibrary/5 as zen
indicator(title = "RektEdge Reversion Band V2", shorttitle = "RektEdge Reversion Band V2", overlay = true)
// --- Inputs ---
var confidence_level = input.float(
2.0,
minval=-1.0,
title="Confidence Level",
group="Confidence",
tooltip="If the combined weight of the checks is equal to or over this value, a signal will plot"
)
// Weighted Checks
var band_trade_weight = input.float(1.0, title="Band Trade Weight", group="Check Weight")
var ma_cross_weight = input.float(1.0, title="MA Cross Weight", group="Check Weight")
var engulfing_weight = input.float(1.0, title="Engulfing Weight", group="Check Weight")
var efficiency_weight = input.float(1.0, title="Efficiency Weight", group="Check Weight")
var pullback_weight = input.float(1.0, title="Pullback Weight", group="Check Weight")
var steep_trend_weight = input.float(
1.0, title="Countertrend Deduction",
tooltip="Deducted from total weight if buying/selling against steep trend",
group="Check Weight"
)
var total_weight = 0.0
// Same Type Avoidance Check
var same_type_avoidance = input.bool(
true,
"Avoid Repeating Same Type Signals",
tooltip="If set to true, signals of the same type as the last signal will be ignored. For example, if the last signal was a buy signal, the next buy signal will be ignored.",
group="Same Type Avoidance Check")
// Trendline
var ma_select = input.string(
defval = "combinedMA",
options = ["combinedMA", "SMA", "EMA"],
title = "Moving Average Type",
tooltip = "Selects the type of moving average trendline",
group="Trendline")
var ma_period = input.int(defval = 36,
title = "Moving Average Period",
minval = 1,
tooltip = "Selects the number of periods for the moving average",
step = 7,
group="Trendline")
// Reversion Band
var trendline_avg_period = input.int(
7,
"Trendline Average Period",
tooltip="Sets period of trendline MA to establish baseline for green/red trend coloring of band",
group="Reversion Band"
)
var band_transparency = input.int(
80,
"Band Transparency",
group="Reversion Band"
)
var delay = input.int(
2,
"Band Delay",
tooltip="Delay the band by this many bars",
minval=0,
group="Reversion Band"
)
var unit_select = input.string(
title = "Unit of Separation",
defval = "ATR",
options = ["ATR","STDEV"],
tooltip = "Selects the unit of separation for the channels",
group="Reversion Band"
)
var atr_period = input(
14,
title="ATR Period",
tooltip="Selects the number of periods for the Average True Range unit and filter pass",
group="Reversion Band"
)
var stdev_period = input.int(
defval = 7,
title = "Standard Deviation Period",
step = 1,
tooltip = "Selects the number of periods for the Standard Deviation separation unit (if selected)",
group="Reversion Band"
)
var unit_mult = input.float(
defval = 2.0,
title = "Multiples of Unit",
step = 0.1,
tooltip = "Select the number of separation units for the channels and the ATR filter",
group="Reversion Band")
// Steep Countertrend Filter
var trend_lookback = input.int(
20,
"Trend Lookback",
group="Countertrend Filter"
)
var steep_factor = input.float(
1.0,
"Steepness Factor",
tooltip="A counter-trend with slope above this threshold will trigger the filter and reduce the total weight. Suggested values: Day(2-3), Swing(1.5-2), Position(1-1.5)",
group="Countertrend Filter"
)
// Is Last Candle Doji
var wickSize = input(
2,
title="Wick Size (in % of candle)",
group="Is Last Candle Doji",
tooltip="Wick size to qualify as Doji")
var bodySize = input(
0.05,
title="Body Size (in % of candle)",
tooltip="Body size to qualify as Doji",
group="Is Last Candle Doji")
// Is Last Candle Hammer or Shooting Star
var fib = input(
0.382,
title="Fib Level",
tooltip="Fib level to qualify as Hammer or Star",
group="Is Last Candle Hammer or Shooting Star",
inline="HammerStar")
var colorMatch = input(
false,
title="Color Match",
tooltip="Require Hammer or Star to also be bullish or bearish respectively",
group="Is Last Candle Hammer or Shooting Star",
inline="HammerStar")
// Efficiency Check
var efficiency_z_threshold = input.float(
0.674,
"Efficiency Z-Score Threshold",
tooltip="A value of 2.0 represents 95% confidence of significance",
group="Efficiency Check"
)
var fractal_z_threshold = input.float(
0.674,
"Fractal Efficiency Z-Score Threshold",
tooltip="A value of 2.0 represents 95% confidence of significance, the default is 75%",
group="Efficiency Check"
)
// Pullback Check
var lookback_pullback = input(
14,
title="Pullback Lookback Period",
group="Pullback Check")
var direction = input(
1,
title="Direction (1=Green, -1=Red)",
tooltip="Pullback bars count direction",
group="Pullback Check")
var pullback_z_threshold = input.float(
0.674,
"Pullback Z-Score Threshold",
tooltip="A value of 2.0 represents 95% confidence of significance, the default is 75%",
group="Pullback Check"
)
// Engulfing Candle Check
var allowance = input(
0,
title="Allowance (in POINTS)",
tooltip="Allows candles off by this many points to still be considered engulfing",
group="Engulfing Candle Check")
var rejectionWickSize = input(
0,
title="Rejection Wick Size (in % of body)",
tooltip="Candles with wicks larger than this size will not be considered engulfing",
group="Engulfing Candle Check")
var engulfWick = input.bool(
false,
"Wick Engulfed Also",
tooltip="Require wick to be engulfed as well",
group="Engulfing Candle Check")
// Bars Above/Below MA Check
var lookback_ma_above = input(
14,
title="MA Above Lookback Period",
group="Bars Above/Below MA Check")
var lookback_ma_below = input(
14,
title="MA Below Lookback Period",
group="Bars Above/Below MA Check")
var lookback_ma_crossed = input(
14,
title="MA Crossed Lookback Period",
group="Bars Above/Below MA Check")
// Indicator Variables
var bool last_signal_is_buy = na
var bool last_signal_is_sell = na
bool is_buy = na
bool is_sell = na
// Calculations
sma = ta.sma(close, ma_period)
ema = ta.ema(close, ma_period)
alpha = 2 / (ma_period + 1)
combined_ma = (alpha * close) + ((1 - alpha) * sma)
trendline = ma_select == "SMA" ? sma : ma_select == "EMA" ? ema : combined_ma
separation = math.abs(unit_mult * (unit_select == "ATR" ? ta.atr(ma_period) : ta.stdev(close,stdev_period)))
long_ema = ta.ema(close, 100)
upper_band = trendline[delay] + separation[delay]
lower_band = trendline[delay] - separation[delay]
[macdLine, signalLine, histLine] = ta.macd(close, 12, 26, 9)
macd_trend_up = macdLine > signalLine and macdLine > 0
macd_trend_down = macdLine < signalLine and macdLine < 0
trendline_diff = trendline - trendline[trend_lookback]
avg_trendline_diff = ta.sma(trendline_diff, trend_lookback)
steep_down = trendline_diff < -avg_trendline_diff * steep_factor
steep_up = trendline_diff > avg_trendline_diff * steep_factor
swingHigh = high[1] == ta.highest(high, ma_period)
swingLow = low[1] == ta.lowest(low, ma_period)
ema_separation = (close - long_ema) / ta.atr(100)
avg_separation = ta.sma(ema_separation, 7)
isAboveLEMA = avg_separation[1] > 1.0
isBelowLEMA = avg_separation[1] < 0 and math.abs(avg_separation[1]) > 1.0
trendline_roc = (trendline - trendline[1]) / (time - time[1])
trendline_avg = ta.sma(trendline, trendline_avg_period)
trending_up = trendline > trendline_avg
trending_down = trendline < trendline_avg
isPivotTop = ta.pivothigh(trendline, 40)
isPivotBottom = ta.pivotlow(trendline,40)
isBelowBand = low[1]<lower_band
isAboveBand = high[1]>upper_band
is_buy := false
is_sell := false
total_weight := 0.0
bars_above_ma_count = ta.barssince(close > sma)
bars_below_ma_count = ta.barssince(close < sma)
pullback_bars_count = 0
direction := 0
efficiency_ratio = stats.efficiencyRatio(close, 14)
fractal_efficiency = stats.fractalEfficiency(close, 30)
bars_crossed_ma_count = zen.barsCrossedMA(lookback_ma_crossed, ma_period)
is_last_candle_doji = zen.isDoji(wickSize, bodySize)
is_last_candle_hammer = zen.isHammer(fib, colorMatch)
is_last_candle_shooting_star = zen.isStar(fib, colorMatch)
is_last_candle_bullish_engulfing = zen.isBullishEC(allowance, rejectionWickSize, engulfWick)
is_last_candle_bearish_engulfing = zen.isBearishEC(allowance, rejectionWickSize, engulfWick)
is_atr_filter_pass = zen.atrFilter(atr_period, unit_mult)
// Check 1: Price below lower band and candle is bullish and swingLow
if is_atr_filter_pass and isBelowBand and (is_last_candle_doji or is_last_candle_bullish_engulfing or is_last_candle_hammer)
is_buy := true
total_weight += band_trade_weight
// Check 2: Price above upper band and candle is bearish and swingHigh
if is_atr_filter_pass and isAboveBand and (is_last_candle_doji or is_last_candle_bearish_engulfing or is_last_candle_shooting_star)
is_sell := true
total_weight += band_trade_weight
// Check 3: Efficiency Ratio and Fractal Efficiency with Statistical Significance
efficiency_z_score = (efficiency_ratio - ta.sma(efficiency_ratio, 100)) / ta.stdev(efficiency_ratio, 100)
fractal_z_score = (fractal_efficiency - ta.sma(fractal_efficiency, 100)) / ta.stdev(fractal_efficiency, 100)
if efficiency_z_score > efficiency_z_threshold and fractal_z_score > fractal_z_threshold and is_last_candle_hammer
total_weight += efficiency_weight
// Check 4: MA Cross and Trend
if bars_crossed_ma_count > 0 and is_last_candle_shooting_star and is_atr_filter_pass and trending_up
is_sell := true
total_weight += ma_cross_weight
else if bars_crossed_ma_count < 0 and is_last_candle_hammer and is_atr_filter_pass and not trending_up
is_buy := true
total_weight += ma_cross_weight
// Check 5: Engulfing
if is_last_candle_bullish_engulfing and is_atr_filter_pass
is_buy := true
total_weight += engulfing_weight
else if is_last_candle_bearish_engulfing and is_atr_filter_pass
is_sell := true
total_weight += engulfing_weight
// Check 6: Pullback with Statistical Significance
pullback_size = high[pullback_bars_count > 0 ? pullback_bars_count - 1 : 0] - low[pullback_bars_count > 0 ? pullback_bars_count - 1 : 0]
pullback_z_score = (pullback_size - ta.sma(pullback_size, 100)) / ta.stdev(pullback_size, 100)
if pullback_bars_count > 1 and is_atr_filter_pass and direction > 0 and pullback_z_score < pullback_z_threshold and is_last_candle_hammer
is_buy := true
total_weight += pullback_weight
else if pullback_bars_count > 1 and is_atr_filter_pass and direction < 0 and pullback_z_score > -pullback_z_threshold and is_last_candle_shooting_star
is_sell := true
total_weight += pullback_weight
// Check 7: Avoid Trading Against A Strong Countertrend
if steep_down and is_buy and not macd_trend_down
total_weight -= steep_trend_weight
else if steep_up and is_sell and not macd_trend_up
total_weight -= steep_trend_weight
// Weighted Sum Check
if total_weight < confidence_level
is_buy := false
is_sell := false
// Check for Same Type Buy/Sell Avoidance
if same_type_avoidance and ((is_buy and last_signal_is_buy) or (is_sell and last_signal_is_sell))
is_buy := false
is_sell := false
// Update last signal
if is_buy
last_signal_is_buy := true
last_signal_is_sell := false
if is_sell
last_signal_is_buy := false
last_signal_is_sell := true
// --- Plots ---
ma_plot = plot(
trendline,
linewidth = 1,
color = color.white,
title = "Moving Average")
upper_plot = plot(upper_band, linewidth = 1, color = color.gray, title = "Upper Band")
lower_plot = plot(lower_band, linewidth = 1, color = color.gray, title = "Lower Band")
//long_plot = plot(long_ema, "Long EMA", color.white)
fill(
plot1 = upper_plot, plot2 = lower_plot,
color = trending_up ? color.new(color.green, band_transparency) :
trending_down ? color.new(color.red, band_transparency) :
color.new(color.gray, band_transparency),
title = "Channel"
)
plotshape(
series = is_buy,
style = shape.triangleup,
color = color.green,
title = "Buy Signal",
display = display.pane,
size=size.tiny,
location=location.belowbar
)
plotshape(
series = is_sell,
style = shape.triangledown,
color = color.red,
title = "Sell Signal",
display = display.pane,
size=size.tiny) |
Negative Correlation Signals | https://www.tradingview.com/script/ZXV6L6K4-Negative-Correlation-Signals/ | Marc_Thiart | https://www.tradingview.com/u/Marc_Thiart/ | 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/
// © Blockhead305
//@version=5
indicator(title="Negative Correlation Signals", shorttitle="Negative Correlation Signals", overlay = true)
instrument_1 = input.symbol(defval = "OANDA:GBPJPY", title = "pair")
instrument_2 = input.symbol(defval = "PEPPERSTONE:JPYX", title = "index")
smoothK = input.int(3, "K", minval=1)
smoothD = input.int(3, "D", minval=1)
lengthRSI = input.int(14, "RSI Length", minval=1)
lengthStoch = input.int(14, "Stochastic Length", minval=1)
[open_1, high_1, low_1, close_1, atr_1] = request.security(instrument_1, timeframe.period, [open, high, low, close, ta.sma(math.abs(open - close), 14)])
[open_2, high_2, low_2, close_2, atr_2] = request.security(instrument_2, timeframe.period, [open, high, low, close, ta.sma(math.abs(open - close), 14)])
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Stoch RSI instrument 1
rsi1 = ta.rsi(close_1, lengthRSI)
k = ta.sma(ta.stoch(rsi1, rsi1, rsi1, lengthStoch), smoothK)
d = ta.sma(k, smoothD)
// plot(k, "K", color=#2962FF)
// plot(d, "D", color=#FF6D00)
// h0 = hline(80, "Upper Band", color=#787B86)
// hline(50, "Middle Band", color=color.new(#787B86, 50))
// h1 = hline(20, "Lower Band", color=#787B86)
// fill(h0, h1, color=color.rgb(33, 150, 243, 90), title="Background")
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Stoch RSI instrument 2
rsi2 = ta.rsi(close_2, lengthRSI)
k_2 = ta.sma(ta.stoch(rsi2, rsi2, rsi2, lengthStoch), smoothK)
d_2 = ta.sma(k_2, smoothD)
// plot(k_2, "K 2", color=#2962FF)
// plot(d_2, "D 2", color=#FF6D00)
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// candles
dominant_wick_multiple = input.float(defval = 2.0, title = "dominant wick multiple", minval = 1.0, maxval = 10.0, step = 0.1, group = "candlestick")
recessive_wick_multiple = input.float(defval = 0.7, title = "recessive wick multiple", minval = 0.1, maxval = 10.0, step = 0.1, group = "candlestick")
body_multiple = input.float(defval = 0.5, title = "body multiple", minval = 0.1, maxval = 10.0, step = 0.1, group = "candlestick")
body_1 = math.abs(close_1 - open_1)
upper_wick_1 = math.abs(math.max(open_1, close_1) - high_1)
lower_wick_1 = math.abs(math.min(open_1, close_1) - low_1)
ATR_upper_wick_1 = ta.sma(upper_wick_1, 200)
ATR_lower_wick_1 = ta.sma(lower_wick_1, 200)
ATR_body_1 = ta.sma(body_1, 200)
upper_wick_dominant_1 = (upper_wick_1 > body_1) and (upper_wick_1 > (ATR_upper_wick_1 * dominant_wick_multiple)) and (body_1 < (ATR_body_1 * body_multiple)) and (lower_wick_1 < (ATR_lower_wick_1 * recessive_wick_multiple))
lower_wick_dominant_1 = (lower_wick_1 > body_1) and (lower_wick_1 > (ATR_lower_wick_1 * dominant_wick_multiple)) and (body_1 < (ATR_body_1 * body_multiple)) and (upper_wick_1 < (ATR_upper_wick_1 * recessive_wick_multiple))
// bgcolor(upper_wick_dominant_1 ? color.green : lower_wick_dominant_1 ? color.red : na)
body_2 = math.abs(close_2 - open_2)
upper_wick_2 = math.abs(math.max(open_2, close_2) - high_2)
lower_wick_2 = math.abs(math.min(open_2, close_2) - low_2)
ATR_upper_wick_2 = ta.sma(upper_wick_2, 200)
ATR_lower_wick_2 = ta.sma(lower_wick_2, 200)
ATR_body_2 = ta.sma(body_2, 200)
upper_wick_dominant_2 = (upper_wick_2 > body_2) and (upper_wick_2 > (ATR_upper_wick_2 * dominant_wick_multiple)) and (body_2 < (ATR_body_2 * body_multiple)) and (lower_wick_2 < (ATR_lower_wick_2 * recessive_wick_multiple))
lower_wick_dominant_2 = (lower_wick_2 > body_2) and (lower_wick_2 > (ATR_lower_wick_2 * dominant_wick_multiple)) and (body_2 < (ATR_body_2 * body_multiple)) and (upper_wick_2 < (ATR_upper_wick_2 * recessive_wick_multiple))
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// signals
k_overbougt_and_dominant_upper_1 = k > 80 and upper_wick_dominant_1
k_oversold_and_dominant_lower_1 = k < 20 and lower_wick_dominant_1
k_overbougt_and_dominant_upper_2 = k_2 > 80 and upper_wick_dominant_2
k_oversold_and_dominant_lower_2 = k_2 < 20 and lower_wick_dominant_2
sell = k_overbougt_and_dominant_upper_1 and k_oversold_and_dominant_lower_2
buy = k_oversold_and_dominant_lower_1 and k_overbougt_and_dominant_upper_2
plotchar(sell, title = "sell", char = "S", location = location.abovebar, color = color.red, size = size.small)
plotchar(buy, title = "buy", char = "B", location = location.belowbar, color = color.green, size = size.small)
// signal_1
if buy and barstate.isconfirmed
alert("buy found", freq = alert.freq_once_per_bar_close)
if sell and barstate.isconfirmed
alert("sell found", freq = alert.freq_once_per_bar_close)
|
Velocity | https://www.tradingview.com/script/uhMVFIIE-Velocity/ | HGabriel_marius | https://www.tradingview.com/u/HGabriel_marius/ | 61 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © HGabriel_marius
//@version=5
indicator("Velocity Change",timeframe = '', format = format.percent)
len = input(3, "Initial Point")
src = input(close)
INI = src[len]
CH = ((close - INI)/INI)*100
OP = input(100, "Length of Upper and Lower")
V = (CH / len)
S = (V - V[len])/len
x = ta.stdev(V, OP)
y = ta.stdev(V, OP) * -1
plot(CH, "Change", color = color.red, display = display.status_line)
plot(V, "Speed", color = color.orange)
//plot(S, "Velocity", color = color.blue)
ZE = plot(0,color = color.rgb(151, 151, 151))
PO = plot(x,color = color.white)
NE = plot(y,color = color.white)
fill(ZE, PO, color = color.rgb(76, 175, 79, 90))
fill(ZE, NE, color = color.rgb(255, 82, 82, 90))
ma(source, length, type) =>
switch type
"SMA" => ta.sma(source, length)
"Bollinger Bands" => 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)
maTypeInput = input.string("SMA", title="MA Type", options=["SMA", "Bollinger Bands", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group="MA Settings")
col1 = color.green
col2 = color.red
col3 = color.blue
col4 = color.purple
VMA = ma(V, len, maTypeInput)
//SMA = ma(S, len, maTypeInput)
trend = VMA[1] > VMA
//trend2 = SMA[1] > SMA
color = trend ? col2 : col1
//color2 = trend2 ? col4 : col3
plot(VMA, "Velocity-based MA", color=color, linewidth = 2)
//plot(SMA, "Speed-based MA", color=color2, linewidth = 2)
|
Profile Any Indicator [Kioseff Trading] | https://www.tradingview.com/script/RSZxyvmd-Profile-Any-Indicator-Kioseff-Trading/ | KioseffTrading | https://www.tradingview.com/u/KioseffTrading/ | 282 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © KioseffTrading
//@version=5
indicator("Profile Any Indicator [Kioseff Trading]", max_boxes_count = 500, max_lines_count = 500)
src = input.source(defval = open, title = "Indicator", group = "Primary Settings")
profSize = input.int (defval = 1, minval = 1, title = "Profile Bar Size", group = "Primary Settings")
rows = input.int (defval = 40, minval = 6, maxval = 500, title = "Rows", step = 25, group = "Primary Settings") - 1
ori = input.string(defval = "Left", title = "Orientation", options = ["Left", "Right"], group = "Primary Settings")
plo = input.bool ( defval = false, title = "Plot My Indicator In The Current Pane", group = "Do You Want To Plot Your Indicator In The Current New Pane?")
ploc = input.color(defval = color.lime, title = "Color", group = "Do You Want To Plot Your Indicator In The Current New Pane?")
nvacol = input.color(defval = color.new(color.blue, 75), title = 'NON-VA Color', group = "NON-VA")
poc = input.bool(defval = true, title = 'POC', group = "POC", inline = "1"),
pocol = input.color(defval = color.new(color.red, 50), group = "POC", title = "", inline = "1"),
pocw = input.int(defval = 2, minval = 1, maxval = 4, title = 'Width', group = "POC", inline = "1")
vcalc = input.float(defval = 70, minval = 5, maxval = 95, title = "Value Area %", group = "Value Area")
val = input.bool(defval = true, title = "VA Lines", group = "Value Area", inline = "2")
vacolL = input.color(defval = color.new(color.blue, 75), title = "", group = "Value Area", inline = "2")
vaw = input.int(defval = 2, minval = 1, maxval = 4, title = "Width", group = "Value Area", inline = "2")
vacol = input.color(defval = color.new(color.yellow, 75), title = '"Value Area" Color', group = "Value Area")
vafill = input.color(defval = color.new(color.gray, 75), title = "Value Area Fill Color", group = "Value Area")
var int [] timeArray = array.new_int()
var float [] dist = array.new_float()
var int [] x2 = array.new_int(rows + 1, 5)
var vh = matrix.new<float>(1, 1)
array.unshift(timeArray, math.round(time))
if time >= chart.left_visible_bar_time and time <= chart.right_visible_bar_time
matrix.add_col(vh)
matrix.set(vh, 0, matrix.columns(vh) - 1, src)
if barstate.islast
[pos, n] = switch ori
"Left" => [chart.left_visible_bar_time , array.indexof(timeArray, chart.left_visible_bar_time)]
=> [chart.right_visible_bar_time, array.indexof(timeArray, chart.right_visible_bar_time)]
calc = (matrix.max(vh) - matrix.min(vh)) / (rows + 1)
for i = 0 to rows
array.push(dist, matrix.min(vh) + (i * calc))
for i = 1 to matrix.columns(vh) - 1
for x = 0 to array.size(dist) - 1
if matrix.get(vh, 0, i) >= matrix.get(vh, 0, i - 1)
if array.get(dist, x) >= matrix.get(vh, 0, i - 1) and array.get(dist, x) <= matrix.get(vh, 0, i)
array.set(x2, x, array.get(x2, x) + profSize)
else
if array.get(dist, x) >= matrix.get(vh, 0, i) and array.get(dist, x) <= matrix.get(vh, 0, i - 1)
array.set(x2, x, array.get(x2, x) + profSize)
boc = array.new_box()
for i = 1 to rows
right = array.get(timeArray, n + array.get(x2, i))
if ori == "Left"
switch math.sign(n - array.get(x2, i))
-1 => right := chart.right_visible_bar_time
=> right := array.get(timeArray, n - array.get(x2, i))
array.push(boc, box.new(pos, array.get(dist, i - 1),
right, array.get(dist, i), xloc = xloc.bar_time, border_color =
nvacol, bgcolor = nvacol
))
if i == rows
array.push(boc, box.new(pos, array.get(dist, array.size(dist) - 1),
right, array.get(dist, array.size(dist) - 1) + calc, xloc = xloc.bar_time, border_color =
nvacol, bgcolor = nvacol
))
array.shift(x2), nx = array.indexof(x2, array.max(x2))
nz = nx - 1, nz2 = 0, nz3 = 0, nz4 = 0
for i = 0 to array.size(x2) - 1
if nz > -1 and nx <= array.size(x2) - 1
switch array.get(x2, nx) >= array.get(x2, nz)
true => nz2 += array.get(x2, nx), nx += 1
=> nz2 += array.get(x2, nz), nz -= 1
else if nz <= -1
nz2 += array.get(x2, nx), nx += 1
else if nx >= array.size(x2)
nz2 += array.get(x2, nz), nz -= 1
if nz2 >= array.sum(x2) * (vcalc / 100)
nz3 := nx <= array.size(x2) - 1 ? nx : array.size(x2) - 1, nz4 := nz <= -1 ? 0 : nz
break
for i = nz3 to nz4
box.set_border_color(array.get(boc, i), vacol)
box.set_bgcolor(array.get(boc, i), vacol)
if poc
var pocL = line(na)
y = math.avg(box.get_top(array.get(boc, array.indexof(x2, array.max(x2)))), box.get_bottom(array.get(boc, array.indexof(x2, array.max(x2)))))
if na(pocL)
pocL := line.new(chart.left_visible_bar_time, y, chart.right_visible_bar_time, y, xloc = xloc.bar_time, color = pocol, width = pocw)
else
line.set_xy1(pocL, chart.left_visible_bar_time, y)
line.set_xy2(pocL, chart.right_visible_bar_time, y)
if val
var vaup = line(na), var vadn = line(na)
ydn = box.get_bottom(array.get(boc, nz3)), yup = box.get_top(array.get(boc, nz4))
if na(vaup)
vadn := line.new(chart.left_visible_bar_time, ydn, chart.right_visible_bar_time, ydn, xloc = xloc.bar_time, color = vacolL, width = vaw)
vaup := line.new(chart.left_visible_bar_time, yup, chart.right_visible_bar_time, yup, xloc = xloc.bar_time, color = vacolL, width = vaw)
else
line.set_xy1(vadn, chart.left_visible_bar_time, ydn), line.set_xy2(vadn, chart.right_visible_bar_time, ydn)
line.set_xy1(vaup, chart.left_visible_bar_time, yup), line.set_xy2(vaup, chart.right_visible_bar_time, yup)
linefill.new(vadn, vaup, vafill)
if src == open
var tab = table.new(position.middle_center, 1, 1)
table.cell(tab, 0, 0, text = "Add Your Indicator In the Settings!", text_size = size.huge, text_color = color.white)
plot(plo ? src : na, color = ploc, title = "My Indicator") |
Major Central Bank Assets [tedtalksmacro] | https://www.tradingview.com/script/1LGLR4Cd-Major-Central-Bank-Assets-tedtalksmacro/ | tedtalksmacro | https://www.tradingview.com/u/tedtalksmacro/ | 202 | 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/
// © tedtalksmacro
//@version=5
indicator("Major Central Bank Assets [tedtalksmacro]", overlay = false, format = format.price)
// Calculate Japan Liquidity
bojassetsopen = request.security("FRED:JPNASSETS * FX_IDC:JPYUSD", "D", open, currency = currency.USD)
bojassetsclose = request.security("FRED:JPNASSETS * FX_IDC:JPYUSD", "D", close, currency = currency.USD)
japan_liquidity = bojassetsclose / 1000000000000
//calculate US liquidity
balance_sheet = request.security("USCBBS", 'D', close)
treasury_gen = request.security("WTREGEN", 'D', close)
rrp = request.security("RRPONTTLD", 'D', close)
usd_liquidity = (balance_sheet) / 1000000000000
net_usd_liquidity = (balance_sheet-treasury_gen-rrp) / 1000000000000
// Calculate Euro Zone Liquidity
ecbassetsopen = request.security("ECBASSETSW * FX:EURUSD", "D", open)
ecbassetsclose = request.security("ECBASSETSW * FX:EURUSD", "D", close)
euro_liquidity = ecbassetsclose / 1000000000000
// Calculate Chinese Liquidity
pbocassetsopen = request.security("CNCBBS * FX_IDC:CNYUSD", "D", open, currency = currency.USD)
pbocassetsclose = request.security("CNCBBS * FX_IDC:CNYUSD", "D", close, currency = currency.USD)
china_liquidity = pbocassetsclose / 1000000000000
// Calculate average assets to smooth out global net effect
global = (china_liquidity + usd_liquidity + euro_liquidity + japan_liquidity) / 4
// plot liquidity
plot(euro_liquidity, style = plot.style_areabr, linewidth=2, color= color.new(color.green, 40), title = 'ECB Assets [tln USD]')
plot(usd_liquidity, style = plot.style_areabr, linewidth=2, color= color.new(color.red, 40), title = 'Fed Assets [tln USD]')
plot(china_liquidity, style = plot.style_areabr, linewidth=2, color= color.new(color.yellow, 40), title = 'PBoC Assets [tln USD]')
plot(japan_liquidity, style = plot.style_areabr, linewidth=2, color= color.new(color.orange, 40), title = 'BOJ Assets [tln USD]')
plot(global, style = plot.style_line, linewidth=2, color= color.new(color.black, 0), title = 'Average Assets [tln USD]')
plot(net_usd_liquidity, style = plot.style_line, linewidth=2, color= color.new(color.blue, 40), title = 'Net USD Liquidity [tln USD]') |
Big 8 Intraday TICK | https://www.tradingview.com/script/BPzxnsVa-Big-8-Intraday-TICK/ | BigGuavaTrading | https://www.tradingview.com/u/BigGuavaTrading/ | 150 | 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/
// © BigGuavaTrading
//@version=5
indicator("Big 8 Intraday TICK", "Big 8 Intraday TICK", false)
hline(0, "Zero line", color.black) //sets 0 line
//Up ticks for each symbol
APup = request.security('AAPL', "", close) > request.security('AAPL', "", close[1]) ? 1 : 0
MEup = request.security('META', "", close) > request.security('META', "", close[1]) ? 1 : 0
MSup = request.security('MSFT', "", close) > request.security('MSFT', "", close[1]) ? 1 : 0
GLup = request.security('GOOGL', "", close) > request.security('GOOGL', "", close[1]) ? 1 : 0
AZup = request.security('AMZN', "", close) > request.security('AMZN', "", close[1]) ? 1 : 0
TSup = request.security('TSLA', "", close) > request.security('TSLA', "", close[1]) ? 1 : 0
NVup = request.security('NVDA', "", close) > request.security('NVDA', "", close[1]) ? 1 : 0
BRup = request.security('BRK.B', "", close) > request.security('BRK.B', "", close[1]) ? 1 : 0
//Down ticks for each symbol
APdn = request.security('AAPL', "", close) < request.security('AAPL', "", close[1]) ? 1 : 0
MEdn = request.security('META', "", close) < request.security('META', "", close[1]) ? 1 : 0
MSdn = request.security('MSFT', "", close) < request.security('MSFT', "", close[1]) ? 1 : 0
GLdn = request.security('GOOGL', "", close) < request.security('GOOGL', "", close[1]) ? 1 : 0
AZdn = request.security('AMZN', "", close) < request.security('AMZN', "", close[1]) ? 1 : 0
TSdn = request.security('TSLA', "", close) < request.security('TSLA', "", close[1]) ? 1 : 0
NVdn = request.security('NVDA', "", close) < request.security('NVDA', "", close[1]) ? 1 : 0
BRdn = request.security('BRK.B', "", close) < request.security('BRK.B', "", close[1]) ? 1 : 0
ticks = APup + MEup + MSup + GLup + AZup + TSup + NVup + BRup - APdn - MEdn - MSdn - GLdn - AZdn - TSdn - NVdn - BRdn //calculates all ticks
//set value at zero and reset at start of day
var cti = 0.0
isMarketOpen = time("1", "0931-1600", "America/New_York")
if isMarketOpen
// Add ticks during market hours
cti := cti + ticks
else
// Reset at end of day
cti := 0.0
c = cti > cti[1] ? color.green : color.red //sets CTI color
plot(cti, 'Big 8 Cumulative Tick', c, 2, plot.style_line) //plots CTI
ctiema = ta.ema(cti, input(15, "EMA of TICK")) //establish CTI EMA for smoothing
b = ctiema > ctiema[1] ? color.blue : color.orange //sets CTI EMA clor
plot(ctiema, "EMA of TICK", b, 3, plot.style_line) //plots CTI EMA
//End |
USD Market Liquidity [tedtalksmacro] | https://www.tradingview.com/script/xM15lR2Y-USD-Market-Liquidity-tedtalksmacro/ | tedtalksmacro | https://www.tradingview.com/u/tedtalksmacro/ | 361 | 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/
// © tedtalksmacro
//@version=5
indicator("Net USD Liquidity [tedtalksmacro]", overlay = false)
//USCBBS-RRPONTTLD*1000000000-WTREGEN*1000000000
balance_sheet = request.security("USCBBS", 'D', close)
treasury_gen = request.security("WTREGEN", 'D', close)
rrp = request.security("RRPONTTLD", 'D', close)
value = (balance_sheet-treasury_gen-rrp) / 1000000000000
var booleish = true
seven_sma = ta.ema(value, 20)
bullish = value > seven_sma
bearish = value < seven_sma
if booleish
if bearish
booleish := false
if not booleish
if bullish
booleish := true
// mycolor = higher ? color.silver : lower ? color.blue : na
sentimentColor = booleish ? color.rgb(101, 171, 103) : color.rgb(197, 10, 10)
plot(value, transp = 0, linewidth=2, color= sentimentColor, title = 'USD Liquidity') |
Investing Performance with vs without fees | https://www.tradingview.com/script/opvlO7CF-Investing-Performance-with-vs-without-fees/ | Daveatt | https://www.tradingview.com/u/Daveatt/ | 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/
// © Daveatt
// Inspiration: https://www.tutorialspoint.com/calculate-compound-interest-in-javascript
//@version=5
indicator("Investing Performance", overlay = false)
i_start_date = input.int(1980, title = "Starting Year")
amount_invested = input.float(5000, title = "Amount invested each year")
annualInterestRate = input.float(10, title = "Average rate of Appreciation") * 0.01
annualManagerFeeRate = input.float(2, title = "Fund Manager Fees") * 0.01
nb_compound_interest = input.int(1, minval = 1, title = "Number of times that interest is compounded per unit", tooltip = "for example if interest is compounded monthly and t is in years then the value of n would be 12. If interest is compounded quarterly and t is in years then the value of n would be 4.")
if timeframe.period != "12M"
runtime.error("The selected chart timeframe must be 12M")
// Made by @RicardoSantos
// Link: https://www.tradingview.com/script/7wlSFTY6-Function-Compound-Interest/
// Description: Calculate compound interest for given values.
//f_compound_interest(_principle, _rate, _duration)=>
// _return = _principle * (math.pow(1 + _rate / 100, _duration))
f_compound_interest(_principle, _rate, _duration, n) =>
_return = _principle * (math.pow((1 + (_rate / n)), (n * _duration)))
var float pnl_without_fees = 0.
var float pnl_with_fees = 0.
yearsElapsed = year(timenow) - i_start_date
var float totalInvested = amount_invested * yearsElapsed
// Calculate the final value of the investment with manager fees
pnl_without_fees := f_compound_interest(amount_invested, annualInterestRate, yearsElapsed, nb_compound_interest)
pnl_with_fees := f_compound_interest(amount_invested, (annualInterestRate - annualManagerFeeRate), yearsElapsed, nb_compound_interest)
plot(annualInterestRate - annualManagerFeeRate, title = "test", display = display.data_window)
var table table_pnl = table.new(position.middle_center, 11, 2, bgcolor = color.white, border_color = color.black, border_width = 2, frame_color = color.black, frame_width = 2)
if barstate.islastconfirmedhistory
pnl_delta = math.abs(pnl_with_fees - pnl_without_fees)
str_yearsElapsed = str.tostring(yearsElapsed)
str_annualInterestRate = str.tostring(annualInterestRate * 100) + "%"
str_annualManagerFeeRate = str.tostring(annualManagerFeeRate * 100) + "%"
str_currentAmountWithFees = str.tostring(pnl_with_fees, "#") + " " + syminfo.currency
str_currentAmountWithoutFees = str.tostring(pnl_without_fees, "#") + " " + syminfo.currency
str_totalInvestedAmount = str.tostring(totalInvested, "#") + " " + syminfo.currency
str_totalAmountWithFees = str.tostring(pnl_with_fees + totalInvested, "#") + " " + syminfo.currency
str_totalAmountWithoutFees = str.tostring(pnl_without_fees + totalInvested, "#") + " " + syminfo.currency
str_pnlDelta = str.tostring(pnl_delta, "#") + " " + syminfo.currency
// Headers
table.cell(table_pnl, 0, 0, text = "Start Year", text_color = color.black, text_size = size.normal, bgcolor = color.orange)
table.cell(table_pnl, 1, 0, text = "End Year", text_color = color.black, text_size = size.normal, bgcolor = color.orange)
table.cell(table_pnl, 2, 0, text = "Elapsed Years", text_color = color.black, text_size = size.normal, bgcolor = color.orange)
table.cell(table_pnl, 3, 0, text = "Total\nInvested Amount", text_color = color.black, text_size = size.normal, bgcolor = color.orange)
table.cell(table_pnl, 4, 0, text = "Annual\nAppreciation Rate", text_color = color.black, text_size = size.normal, bgcolor = color.orange)
table.cell(table_pnl, 5, 0, text = "Annual\nFund Manager Rate", text_color = color.black, text_size = size.normal, bgcolor = color.orange)
table.cell(table_pnl, 6, 0, text = "Cumulative\nPnl Without Fees", text_color = color.black, text_size = size.normal, bgcolor = color.orange)
table.cell(table_pnl, 7, 0, text = "Cumulative\nPnl With Fees", text_color = color.black, text_size = size.normal, bgcolor = color.orange)
table.cell(table_pnl, 8, 0, text = "Principle\n+ Pnl Without Fees", text_color = color.black, text_size = size.normal, bgcolor = color.orange)
table.cell(table_pnl, 9, 0, text = "Principle\n+ Pnl With Fees", text_color = color.black, text_size = size.normal, bgcolor = color.orange)
table.cell(table_pnl, 10, 0, text = "Delta", text_color = color.black, text_size = size.normal, bgcolor = color.orange)
// Data
table.cell(table_pnl, 0, 1, text = str.tostring(i_start_date), text_color = color.black, text_size = size.normal, bgcolor = color.white)
table.cell(table_pnl, 1, 1, text = str.tostring(year(timenow)), text_color = color.black, text_size = size.normal, bgcolor = color.white)
table.cell(table_pnl, 2, 1, text = str_yearsElapsed, text_color = color.black, text_size = size.normal, bgcolor = color.white)
table.cell(table_pnl, 3, 1, text = str_totalInvestedAmount, text_color = color.black, text_size = size.normal, bgcolor = color.white)
table.cell(table_pnl, 4, 1, text = str_annualInterestRate, text_color = color.black, text_size = size.normal, bgcolor = color.white)
table.cell(table_pnl, 5, 1, text = str_annualManagerFeeRate, text_color = color.black, text_size = size.normal, bgcolor = color.white)
table.cell(table_pnl, 6, 1, text = str_currentAmountWithoutFees, text_color = color.black, text_size = size.normal, bgcolor = color.white)
table.cell(table_pnl, 7, 1, text = str_currentAmountWithFees, text_color = color.black, text_size = size.normal, bgcolor = color.white)
table.cell(table_pnl, 8, 1, text = str_totalAmountWithoutFees, text_color = color.black, text_size = size.normal, bgcolor = color.white)
table.cell(table_pnl, 9, 1, text = str_totalAmountWithFees, text_color = color.black, text_size = size.normal, bgcolor = color.white)
table.cell(table_pnl, 10, 1, text = str_pnlDelta, text_color = color.black, text_size = size.normal, bgcolor = color.white) |
ICT Implied Fair Value Gap (IFVG) [LuxAlgo] | https://www.tradingview.com/script/1KtO6NVA-ICT-Implied-Fair-Value-Gap-IFVG-LuxAlgo/ | LuxAlgo | https://www.tradingview.com/u/LuxAlgo/ | 3,245 | study | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © LuxAlgo
//@version=5
indicator("ICT Implied Fair Value Gap (IFVG) [LuxAlgo]", overlay = true
, max_lines_count = 500
, max_boxes_count = 500)
//------------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
thr = input.float(30, 'Shadow Threshold %', minval = 0, maxval = 100) / 100
ext = input(8, 'IFVG Extension')
extAvg = input(false, 'Extend Averages')
//Style
showBull = input(true, 'Bullish IFVG' , inline = 'bull', group = 'Style')
bullZone = input(color.new(#3179f5, 50), '', inline = 'bull', group = 'Style')
bullAvg = input(#3179f5, '' , inline = 'bull', group = 'Style')
showBear = input(true, 'Bearish IFVG' , inline = 'bear', group = 'Style')
bearZone = input(color.new(#ff5d00, 50), '', inline = 'bear', group = 'Style')
bearAvg = input(#ff5d00, '' , inline = 'bear', group = 'Style')
//-----------------------------------------------------------------------------}
//Detection Rules
//-----------------------------------------------------------------------------{
n = bar_index
r = high - low
b = math.abs(close - open)
//Bullish IFVG
bull_top = math.avg(math.min(close, open), low)
bull_btm = math.avg(math.max(close[2], open[2]), high[2])
bull_ifvg = b[1] > math.max(b, b[2])
and low < high[2]
and (math.min(close, open) - low) / r > thr
and (high[2] - math.max(close[2], open[2])) / r > thr
and bull_top > bull_btm
//Bearish IFVG
bear_top = math.avg(math.min(close[2], open[2]), low[2])
bear_btm = math.avg(math.max(close, open), high)
bear_ifvg = b[1] > math.max(b, b[2])
and high > low[2]
and (high - math.max(close, open)) / r > thr
and (math.min(close[2], open[2]) - low[2]) / r > thr
and bear_top > bear_btm
//-----------------------------------------------------------------------------}
//Display IFVG's
//-----------------------------------------------------------------------------{
var float bull_ifvg_avg = na
var float bear_ifvg_avg = na
if bull_ifvg and showBull
bull_ifvg_avg := math.avg(bull_top, bull_btm)
//Zone
box.new(n-2, bull_top, n+ext, bull_btm
, border_color = bullAvg
, bgcolor = bullZone)
//Average
line.new(n-2, bull_ifvg_avg, n+ext, bull_ifvg_avg
, color = bullAvg)
if bear_ifvg and showBear
bear_ifvg_avg := math.avg(bear_top, bear_btm)
//Zone
box.new(n-2, bear_top, n+ext, bear_btm
, border_color = bearAvg
, bgcolor = bearZone)
//Average
line.new(n-2, bear_ifvg_avg, n+ext, bear_ifvg_avg
, color = bearAvg)
//-----------------------------------------------------------------------------}
//Plots
//-----------------------------------------------------------------------------{
plot(bull_ifvg_avg, 'Bullish IFVG Average'
, ta.barssince(bull_ifvg) > ext and extAvg ? bullAvg : na)
plot(bear_ifvg_avg, 'Bearish IFVG Average'
, ta.barssince(bear_ifvg) > ext and extAvg ? bearAvg : na)
//-----------------------------------------------------------------------------}
//Alerts
//-----------------------------------------------------------------------------{
alertcondition(bull_ifvg, 'Bullish IFVG', 'Bullish IFVG detected')
alertcondition(bear_ifvg, 'Bearish IFVG', 'Bearish IFVG detected')
//-----------------------------------------------------------------------------} |
ICT Opening Gaps [MK] | https://www.tradingview.com/script/iZiHlcag-ICT-Opening-Gaps-MK/ | malk1903 | https://www.tradingview.com/u/malk1903/ | 513 | 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/
// © malk1903
//@version=5
indicator(title="ICT Opening Gaps [MK]", shorttitle = 'NWOG/NDOG/VI [MK]',overlay=true, max_boxes_count = 500, max_labels_count = 500)
i_maxtf = 1440
disp = timeframe.isintraday and timeframe.multiplier <= i_maxtf
volimba = input.bool(defval=true, title='Daily Volume Imbalance', group='Enable/Disable Section---------------------------------------------', inline = '01')
MOG = input.bool(defval=true, title='NMOG', group='Enable/Disable Section---------------------------------------------', inline = '01b')
prevgaps_m = input.int(20, "", group='Enable/Disable Section---------------------------------------------', inline = '01b')
bool showOnHistory_m = input.bool(true, "Show Previous NMOGs", group='Enable/Disable Section---------------------------------------------', inline = '01b')
WOG = input.bool(defval=true, title='NWOG', group='Enable/Disable Section---------------------------------------------', inline = '02')
prevgaps = input.int(5, "", group='Enable/Disable Section---------------------------------------------', inline = '02')
bool showOnHistory = input.bool(true, "Show Previous NWOGs", group='Enable/Disable Section---------------------------------------------', inline = '02')
sessiongaps = input.bool(defval=true, title='NDOG', group='Enable/Disable Section---------------------------------------------', inline = '03')
prevgapsdy = input.int(5, "", group='Enable/Disable Section---------------------------------------------', inline = '03')
bool showOnHistorydy = input.bool(false, "Show Previous NDOGs", group='Enable/Disable Section---------------------------------------------', inline = '03')
showBox = input.bool(true, "RTH Opening Gap ", group='Enable/Disable Section---------------------------------------------', inline = '05', tooltip = "Shows the standard RTH gap from the close at 4pm to 9:30am open (New York Time)")
timeZone = input.string("GMT-4", title="Time Zone", options=["GMT-10","GMT-9","GMT-8","GMT-7","GMT-6","GMT-5","GMT-4","GMT-3","GMT-2","GMT-1","GMT","GMT+1","GMT+2","GMT+3","GMT+4","GMT+5","GMT+6","GMT+7","GMT+8","GMT+9","GMT+10"], group="Timezone")
/////////////////////////////////////////////Volume Imbalances
boxlength = 1
viMaxBoxSet = input.int(defval=6, title="Maximum VI Box Displayed", group='Daily Volume Imbalances-----------------------------------------', inline='1')
mitig_typeVI = "Body"
UseBodyForMitigationVI = mitig_typeVI == "Body" ? true : false
VOLimb_extend = true
tfvi = "D"
color c_box = input.color(color.new(color.silver,30), 'Volume Imbalance Box', group='Daily Volume Imbalances-----------------------------------------', inline='3')
color c_bord = input.color(color.new(color.silver,100), 'Volume Imbalance Border', group='Daily Volume Imbalances-----------------------------------------', inline='3')
color mit_c = input.color(color.new(color.orange,100), title = 'Fully Mitigated Box', group='Daily Volume Imbalances-----------------------------------------', inline='4')
color mitbord_c = input.color(color.new(color.orange,100), title = 'Fully Mitigated Border', group='Daily Volume Imbalances-----------------------------------------', inline='4', tooltip ="Full mitigation is when imbalance has been passed through with buy side + sell side")
i_BoxBordervi = input.string(defval="solid (─)", title="", options=["solid (─)", "dotted (┈)", "dashed (╌)"], group='Daily Volume Imbalances-----------------------------------------', inline="5")
BoxBorderw = input.int(defval=0, title="Width", minval = 0,maxval =4, step = 1, group='Daily Volume Imbalances-----------------------------------------', inline='5')
novolsun = input.bool(defval=true, title="Dont Show Daily Volume Imbalance on top of New Week Open Gap", tooltip="Daily Volume Imbalances and New Week Opening Gaps will both be displayed in the same area, Enabling this checkbox will remove the Daily volume imbalance so it does not overlap the New Week Opening Gap", inline="6")
plotBoxLabelvi = false
BoxLabelColorvi = color.new(color.white,0)
BoxLabelSizevi = size.small
var box[] greenboxes = array.new_box()
var box[] redboxes = array.new_box()
line_style_function(input_var) =>
switch input_var
"dotted (┈)" => line.style_dotted
"dashed (╌)" => line.style_dashed
=> line.style_solid
BoxBordervi = line_style_function(i_BoxBordervi)
//Data
open0 = request.security(syminfo.tickerid, tfvi, open[0], barmerge.gaps_on, barmerge.lookahead_on)
open1 = request.security(syminfo.tickerid, tfvi, open[1], barmerge.gaps_on, barmerge.lookahead_on)
high0 = request.security(syminfo.tickerid, tfvi, high[0], barmerge.gaps_on, barmerge.lookahead_on)
high1 = request.security(syminfo.tickerid, tfvi, high[1], barmerge.gaps_on, barmerge.lookahead_on)
low0 = request.security(syminfo.tickerid, tfvi, low[0], barmerge.gaps_on, barmerge.lookahead_on)
low1 = request.security(syminfo.tickerid, tfvi, low[1], barmerge.gaps_on, barmerge.lookahead_on)
close0 = request.security(syminfo.tickerid, tfvi, close[0], barmerge.gaps_on, barmerge.lookahead_on)
close1 = request.security(syminfo.tickerid, tfvi, close[1], barmerge.gaps_on, barmerge.lookahead_on)
UpVoid_old = close1 < open0
UpVoid = open0 > close1 and low0 <= high1 and close0 > close1 and open0 > open1
UpVoidsize = open0 - close1
//is candle and precandle both red or both green
bothred = false
bothgreen = false
if close0 > open0 and close1 > open1
bothgreen := true
if (close0 < open0 and close1 < open1) //or (close0 < open0 and close1 < open1)
bothred := true
//timeframe good
tfgoodwk = false
if not timeframe.isweekly
tfgoodwk := true
tfgoodmth = false
if not timeframe.ismonthly
tfgoodmth :=true
//is first candle[1] green or red?
col_1grn = false
if close1 > open1
col_1grn := true
col_0grn = false
if close0 > open0
col_0grn := true
VIMB_SUN = time('1', "1800-1801",timeZone)//Time input used for removing D volume imbalance/Sunday Opening Gap overlap
if UpVoid and UpVoidsize > 0 and volimba and tfgoodwk and tfgoodmth //and disp//and novimb
BOX1 = box.new(left=bar_index[1], top=col_0grn ? open0 : close0, right=bar_index[0] + boxlength, bottom = col_1grn ? close1 : open1, border_style=BoxBordervi, text_halign=text.align_right, text_valign=text.align_center, text_size=BoxLabelSizevi, text_color=BoxLabelColorvi, border_width = BoxBorderw)
if VIMB_SUN and novolsun
box.set_bgcolor(BOX1, color.new(color.black,100))
box.set_border_color(BOX1, color.new(color.black,100))
else
box.set_bgcolor(BOX1, c_box)
box.set_border_color(BOX1, c_bord)
if array.size(greenboxes) > viMaxBoxSet
box.delete(array.shift(greenboxes))
array.push(greenboxes, BOX1)
BottomVoid_old = close1 > open0
BottomVoid = open0 < close1 and open0 < open1 and high0 >= low1 and close0 < close1 and close0 < open1
BottomVoidsize = close1 - open0
//
if BottomVoid and BottomVoidsize > 0 and volimba and tfgoodwk and tfgoodmth //and disp //and novimb
BOX2 = box.new(left=bar_index[1], top = col_1grn ? open1 : close1, right=bar_index[0] + boxlength, bottom=col_0grn ? close0 : open0, border_style=BoxBordervi, text_halign=text.align_right, text_valign=text.align_center, text_size=BoxLabelSizevi, text_color=BoxLabelColorvi, border_width = BoxBorderw)
if VIMB_SUN and novolsun
box.set_bgcolor(BOX2, color.new(color.black,100))
box.set_border_color(BOX2, color.new(color.black,100))
else
box.set_bgcolor(BOX2, c_box)
box.set_border_color(BOX2, c_bord)
if array.size(redboxes) > viMaxBoxSet
box.delete(array.shift(redboxes))
array.push(redboxes, BOX2)
if barstate.isconfirmed //and tfgood3
if array.size(greenboxes) > 0
for i = array.size(greenboxes) - 1 to 0 by 1
tbox2 = array.get(greenboxes, i)
top2 = box.get_top(tbox2)
bottom2 = box.get_bottom(tbox2)
ago2 = box.get_left(tbox2)
if VOLimb_extend
box.set_right(tbox2, bar_index + 1)
//////////////////Use body for mitigation
//greenboxes+red candle
redc = open0-close0
greenc = close0-open0
if UseBodyForMitigationVI
//greenboxes+red candle
if (open0 > top2 and close0 < bottom2 and redc>0) or (open0 < bottom2 and close0 > top2 and greenc>0)
box.set_bgcolor(tbox2,mit_c)
box.set_border_color(tbox2, mitbord_c)
box.set_right(tbox2, last_bar_index)
// //greenboxes+green candle
// if open0 < bottom2 and close0 > top2 and greenc>0
// box.set_bgcolor(tbox2,mit_c)
// box.set_border_color(tbox2, mitbord_c)
// box.set_text_color(tbox2, mitbord_c)
// box.set_right(tbox2, last_bar_index)
// array.remove(greenboxes, i)
if not UseBodyForMitigationVI
//greenboxes+red candle
if (high0 > top2 and low0 < bottom2 and redc>0) or (low0 < bottom2 and high0 > top2 and greenc>0)
box.set_bgcolor(tbox2,mit_c)
box.set_border_color(tbox2, mitbord_c)
box.set_right(tbox2, last_bar_index)
// //greenboxes+green candle
// if low0 < bottom2 and high0 > top2 and greenc>0
// box.set_bgcolor(tbox2,mit_c)
// box.set_border_color(tbox2, mitbord_c)
// box.set_text_color(tbox2, mitbord_c)
// box.set_right(tbox2, last_bar_index)
// array.remove(greenboxes, i)
if array.size(redboxes) > 0 //and UseBodyForMitigationVI
for i = array.size(redboxes) - 1 to 0 by 1
tbox3 = array.get(redboxes, i)
top3 = box.get_top(tbox3)
bottom3 = box.get_bottom(tbox3)
ago3 = box.get_left(tbox3)
redc = open0-close0
greenc = close0-open0
if VOLimb_extend
box.set_right(tbox3, bar_index + 1)
//redboxes+green candle
if UseBodyForMitigationVI
if (open0 < bottom3 and close0 > top3 and greenc>0) or (open0 > top3 and close0 < bottom3 and redc>0)//and UseBodyForMitigationVI
box.set_bgcolor(tbox3,mit_c)
box.set_border_color(tbox3, mitbord_c)
box.set_right(tbox3, last_bar_index)
// //redboxes+red candle
// if open0 > top3 and close0 < bottom3 and redc>0 //and UseBodyForMitigationVI
// box.set_bgcolor(tbox3,mit_c)
// box.set_border_color(tbox3,mit_c)
// box.set_text_color(tbox3, mitbord_c)
// box.set_right(tbox3, last_bar_index)
// array.remove(redboxes, i)
if not UseBodyForMitigationVI
//redboxes+green candle
if (low0 < bottom3 and high0 > top3 and greenc>0) or (high0 > top3 and low0 < bottom3 and redc>0)
box.set_bgcolor(tbox3,mit_c)
box.set_border_color(tbox3, mitbord_c)
box.set_right(tbox3, last_bar_index)
// //redboxes+red candle
// if high0 > top3 and low0 < bottom3 and redc>0
// box.set_bgcolor(tbox3,mit_c)
// box.set_border_color(tbox3,mit_c)
// box.set_text_color(tbox3, mitbord_c)
// box.set_right(tbox3, last_bar_index)
// array.remove(redboxes, i)
////////////////////////////////////////////////////////////////////////////////////New Week Opening Gap
isNewbar(res) =>
t = time(res)
not na(t) and (na(t[1]) or t > t[1])
type gap
float high
float low
int start
int end
color boxBg_curr = input.color(color.new(color.aqua,70), "Current", group = "New Week Opening Gap----------------------------------------------", inline="3")
color boxBg = input.color(color.new(color.blue,80), "Box", group = "New Week Opening Gap----------------------------------------------", inline="3")
color boxBc = input.color(color.new(color.white,100), "Border", group = "New Week Opening Gap----------------------------------------------", inline="3")
i_BoxBordernw = input.string(defval="solid (─)", title="", options=["solid (─)", "dotted (┈)", "dashed (╌)"], group = "New Week Opening Gap----------------------------------------------", inline="3")
BoxBorderwnw = input.int(defval=1, title="Width", minval = 1,maxval =4, step = 1, group = "New Week Opening Gap----------------------------------------------", inline='3')
color boxMl = input.color(color.new(color.silver,0), "Midline", group = "New Week Opening Gap----------------------------------------------", inline="4")
i_mid_line_style = input.string(defval="dotted (┈)", title="", options=["solid (─)", "dotted (┈)", "dashed (╌)"], group = "New Week Opening Gap----------------------------------------------", inline="4")
mid_line_width = input.int(2, "Width", group = "New Week Opening Gap----------------------------------------------", inline="4")
showhlprices = input.bool(defval=false, title="Show H/L price labels")
BoxBordernw = line_style_function(i_BoxBordernw)
mid_line_style = line_style_function(i_mid_line_style)
getGapData() =>
gap.new(math.max(close[1], open), math.min(close[1], open), time, time_close)
gap weeklyOpenGap = request.security(syminfo.tickerid, "1W", getGapData(), lookahead = barmerge.lookahead_on)
int currentDayTimeClose = request.security(syminfo.tickerid, "1D", time_close, lookahead = barmerge.lookahead_on)
var box[] sgbox = array.new_box()
var line[] sgline = array.new_line()
var label[] p_labelsh = array.new_label()
var label[] p_labelsl = array.new_label()
var line gapmid = na
var label plabelsh = na
linegap = 0.0
linegap := (weeklyOpenGap.high+weeklyOpenGap.low)/2
if isNewbar("W") and (timeframe.isdaily or timeframe.isintraday) and WOG and disp
weeklyOpenGapBox = box.new(bar_index, weeklyOpenGap.high, last_bar_index, weeklyOpenGap.low, xloc = xloc.bar_index, bgcolor = boxBg_curr, border_width = 1, border_color = boxBc)
if showhlprices
plabelsh :=label.new(last_bar_index,linegap, text="high: " + str.tostring(weeklyOpenGap.high) + " low: " + str.tostring(weeklyOpenGap.low), xloc=xloc.bar_index, style=label.style_label_left, size=size.normal)
//plabelsl :=label.new(last_bar_index,linegap, text=str.tostring(weeklyOpenGap.low), xloc=xloc.bar_index, style=label.style_label_up)
if array.size(sgbox) > prevgaps
box.delete(array.shift(sgbox))
box.set_bgcolor(weeklyOpenGapBox[1],color.white)
//box.set_right(sgbox, last_bar_index)
array.push(sgbox, weeklyOpenGapBox)
if array.size(p_labelsh) > prevgaps
label.delete(array.shift(p_labelsh))
array.push(p_labelsh, plabelsh)
gapmid := line.new(x1=bar_index, y1=linegap, x2= last_bar_index, y2=linegap, xloc=xloc.bar_index, color=boxMl, style=mid_line_style, width=mid_line_width)
if array.size(sgline) > prevgaps
line.delete(array.shift(sgline))
array.push(sgline, gapmid)
if not showOnHistory
box.delete(weeklyOpenGapBox[1])
line.delete(gapmid[1])
highlight=true
if highlight
box.set_bgcolor(weeklyOpenGapBox[1],boxBg)
////////////////////////////////////////////////////////////////////////////////////New Month Opening Gap
color boxBg_curr_m = input.color(color.new(color.lime,30), "Current", group = "New Month Opening Gap--------------------------------------------", inline="3")
color boxBg_m = input.color(color.new(color.lime,50), "Box", group = "New Month Opening Gap--------------------------------------------", inline="3")
color boxBc_m = input.color(color.new(color.white,100), "Border", group = "New Month Opening Gap--------------------------------------------", inline="3")
i_BoxBordernw_m = input.string(defval="solid (─)", title="", options=["solid (─)", "dotted (┈)", "dashed (╌)"], group = "New Month Opening Gap--------------------------------------------", inline="3")
BoxBorderwnw_m = input.int(defval=1, title="Width", minval = 1,maxval =4, step = 1, group = "New Month Opening Gap--------------------------------------------", inline='3')
color boxMl_m = input.color(color.new(color.silver,0), "Midline", group = "New Month Opening Gap--------------------------------------------", inline="4")
i_mid_line_style_m = input.string(defval="dotted (┈)", title="", options=["solid (─)", "dotted (┈)", "dashed (╌)"], group = "New Month Opening Gap--------------------------------------------", inline="4")
mid_line_width_m = input.int(2, "Width", group = "New Month Opening Gap--------------------------------------------", inline="4")
showhlprices_m = input.bool(defval=false, title="Show H/L price labels", group = "New Month Opening Gap--------------------------------------------", inline="4")
BoxBordernw_m = line_style_function(i_BoxBordernw_m)
mid_line_style_m = line_style_function(i_mid_line_style_m)
gap monthlyOpenGap = request.security(syminfo.tickerid, "M", getGapData(), lookahead = barmerge.lookahead_on)
var box[] sgbox_m = array.new_box()
var line[] sgline_m = array.new_line()
var label[] p_labelsh_m = array.new_label()
var label[] p_labelsl_m = array.new_label()
var line gapmid_m = na
var label plabelsh_m = na
linegap_m = 0.0
linegap_m := (monthlyOpenGap.high+monthlyOpenGap.low)/2
if isNewbar("M") and (timeframe.isdaily or timeframe.isintraday or timeframe.isweekly or timeframe.ismonthly) and MOG //and disp
monthlyOpenGapBox = box.new(bar_index, monthlyOpenGap.high, last_bar_index, monthlyOpenGap.low, xloc = xloc.bar_index, bgcolor = boxBg_curr_m, border_width = BoxBorderwnw_m, border_color = boxBc_m)
if showhlprices_m
plabelsh_m :=label.new(last_bar_index,linegap_m, text="high: " + str.tostring(monthlyOpenGap.high) + " low: " + str.tostring(monthlyOpenGap.low), xloc=xloc.bar_index, style=label.style_label_left, size=size.normal)
//plabelsl :=label.new(last_bar_index,linegap, text=str.tostring(weeklyOpenGap.low), xloc=xloc.bar_index, style=label.style_label_up)
if array.size(sgbox_m) > prevgaps_m
box.delete(array.shift(sgbox_m))
box.set_bgcolor(monthlyOpenGapBox[1],color.white)
//box.set_right(sgbox, last_bar_index)
array.push(sgbox_m, monthlyOpenGapBox)
if array.size(p_labelsh_m) > prevgaps_m
label.delete(array.shift(p_labelsh_m))
array.push(p_labelsh_m, plabelsh_m)
gapmid_m := line.new(x1=bar_index, y1=linegap_m, x2= last_bar_index, y2=linegap_m, xloc=xloc.bar_index, color=boxMl_m, style=mid_line_style_m, width=mid_line_width_m)
if array.size(sgline_m) > prevgaps_m
line.delete(array.shift(sgline_m))
array.push(sgline_m, gapmid_m)
if not showOnHistory_m
box.delete(monthlyOpenGapBox[1])
line.delete(gapmid_m[1])
highlight=true
if highlight
box.set_bgcolor(monthlyOpenGapBox[1],boxBg_m)
////////////////////////////////////////////////////////////////////////////////////Daily Opening Gap
color boxBg_currdy = input.color(color.new(color.white,100), "Current", group = "New Day Opening Gap----------------------------------------------", inline="3")
color boxBgdy = input.color(color.new(color.red,100), "Box", group = "New Day Opening Gap----------------------------------------------", inline="3")
color boxBcdy = input.color(color.new(color.white,100), "Border", group = "New Day Opening Gap----------------------------------------------", inline="3")
i_BoxBorderdy = input.string(defval="solid (─)", title="", options=["solid (─)", "dotted (┈)", "dashed (╌)"], group = "New Day Opening Gap----------------------------------------------", inline="3")
BoxBorderwdy = input.int(defval=1, title="Width", minval = 1,maxval =4, step = 1, group = "New Day Opening Gap----------------------------------------------", inline='3')
color day_hl = input.color(color.new(color.red,0), "High/Low", group = "New Day Opening Gap----------------------------------------------", inline="4")
i_day_line_style = input.string(defval="solid (─)", title="", options=["solid (─)", "dotted (┈)", "dashed (╌)"], group = "New Day Opening Gap----------------------------------------------", inline="4")
day_line_width = input.int(2, "Width", group = "New Day Opening Gap----------------------------------------------", inline="4")
showhlpricesdy = input.bool(defval=false, title="Show H/L price labels", group = "New Day Opening Gap----------------------------------------------", inline="5")
NDOG_sym = input.bool(defval=true,title="⭐ Symbol for Current NDOG", group = "New Day Opening Gap----------------------------------------------", inline="5")
BoxBorderdy = line_style_function(i_BoxBorderdy)
day_line_style = line_style_function(i_day_line_style)
gap dailyOpenGap = request.security(syminfo.tickerid, "1D", getGapData(), lookahead = barmerge.lookahead_on)
var box[] sgboxdy = array.new_box()
var line[] hi_linedy = array.new_line()
var line[] lo_linedy = array.new_line()
var label[] p_labelshdy = array.new_label()
var label[] p_labelsldy = array.new_label()
var line d_hi = na
var line d_lo = na
var label plabelshdy = na
var label label_sym = na
linegapdy = 0.0
linegapdy := (dailyOpenGap.high+dailyOpenGap.low)/2
isMon() => dayofweek(time('D',"","America/New_York"), ("GMT-4")) == dayofweek.monday and close ? 1 : 0
isTue() => dayofweek(time('D',"","America/New_York"), ("GMT-4")) == dayofweek.tuesday and close ? 1 : 0
isWed() => dayofweek(time('D',"","America/New_York"), ("GMT-4")) == dayofweek.wednesday and close ? 1 : 0
isThu() => dayofweek(time('D',"","America/New_York"), ("GMT-4")) == dayofweek.thursday and close ? 1 : 0
isFri() => dayofweek(time('D',"","America/New_York"), ("GMT-4")) == dayofweek.friday and close ? 1 : 0
isSun() => dayofweek(time('D',"","America/New_York"), ("GMT-4")) == dayofweek.sunday and close ? 1 : 0
weekdays = isMon() or isTue() or isWed() or isThu() or isFri() or isSun()
if isNewbar("D") and (timeframe.isdaily or timeframe.isintraday) and sessiongaps and weekdays and disp
dailyOpenGapBox = box.new(bar_index, dailyOpenGap.high, last_bar_index, dailyOpenGap.low, xloc = xloc.bar_index, bgcolor = boxBg_currdy, border_width = BoxBorderwdy, border_color = boxBcdy)
if showhlpricesdy
plabelshdy :=label.new(last_bar_index,linegapdy, text="high: " + str.tostring(dailyOpenGap.high) + " low: " + str.tostring(dailyOpenGap.low), xloc=xloc.bar_index, style=label.style_label_left, size=size.normal, color=color.red)
if array.size(sgboxdy) > prevgapsdy
box.delete(array.shift(sgboxdy))
box.set_bgcolor(dailyOpenGapBox[1],color.white)
array.push(sgboxdy, dailyOpenGapBox)
if array.size(p_labelshdy) > prevgapsdy
label.delete(array.shift(p_labelshdy))
array.push(p_labelshdy, plabelshdy)
d_hi := line.new(x1=bar_index, y1=dailyOpenGap.high, x2= last_bar_index, y2=dailyOpenGap.high, xloc=xloc.bar_index, color=day_hl, style=day_line_style, width=day_line_width)
d_lo := line.new(x1=bar_index, y1=dailyOpenGap.low, x2= last_bar_index, y2=dailyOpenGap.low, xloc=xloc.bar_index, color=day_hl, style=day_line_style, width=day_line_width)
if array.size(hi_linedy) > prevgapsdy
line.delete(array.shift(hi_linedy))
array.push(hi_linedy, d_hi)
if array.size(lo_linedy) > prevgapsdy
line.delete(array.shift(lo_linedy))
array.push(lo_linedy, d_lo)
if NDOG_sym
label_sym := label.new(x=last_bar_index, y=(dailyOpenGap.high+dailyOpenGap.low) / 2, text='⭐', xloc=xloc.bar_index, color=color.new(color.yellow,100), textcolor=color.white,size=size.normal, textalign = text.align_center, style=label.style_label_left)
label.delete(label_sym[1])
if not showOnHistorydy
box.delete(dailyOpenGapBox[1])
line.delete(d_hi[1])
line.delete(d_lo[1])
highlight=true
if highlight
box.set_bgcolor(dailyOpenGapBox[1],boxBgdy)
///////////////////////////////////////////////////////////RTH Gaps II
longDay = 24*1000*3600
isSPY = str.tostring(syminfo.ticker) =="SPY"? true:false
_16_15= timestamp(timeZone, year, month, dayofmonth, 16, 15, 00)
_9_30 = timestamp(timeZone, year, month, dayofmonth, 9, 30, 00)
colorNone = color.new(color.white, 100)
boxColor = input.color(color.new(color.purple, 75), "Standard Gap Box", inline ='-1', group = 'RTH Gaps II---------------------------------------------')
borderColor=input.color(color.new(color.purple, 0), "Border", inline ='-1', group = 'RTH Gaps II---------------------------------------------')
border_w = input.int(defval=1, minval=1, maxval=4, step =1, title='Width', inline ='-1', group = 'RTH Gaps II---------------------------------------------')
boxesToShow =input.int(3, "Historical Boxes to Show", inline = '1', group = 'RTH Gaps II---------------------------------------------')
showTxt = input.bool(true, "Text", inline='2', group = 'RTH Gaps II---------------------------------------------')
boxTxtCol = input.color(color.new(color.gray, 30), "", inline ='2', group = 'RTH Gaps II---------------------------------------------')
ext_lb = input.bool(false, title="Extend Boxes to Current Bar", inline ='2', group = 'RTH Gaps II---------------------------------------------')
hoursfwd = input.float(defval=1, minval=0.5, maxval=6.5, step=0.5, title="Project Hours Forward", inline ='2', group = 'RTH Gaps II---------------------------------------------')
RThmid_cl = input.color(color.new(color.white,0), "Midline", inline ='3', group = 'RTH Gaps II---------------------------------------------')
i_RTHmid_line_style = input.string(defval="solid (─)", title="", options=["solid (─)", "dotted (┈)", "dashed (╌)"], inline ='3', group = 'RTH Gaps II---------------------------------------------')
RTHmid_line_width = input.int(2, "Width", inline ='3', group = 'RTH Gaps II---------------------------------------------')
RTh2575_cl = input.color(color.new(color.white,0), "25%/75%", inline ='4', group = 'RTH Gaps II---------------------------------------------')
i_RTH2575_line_style = input.string(defval="solid (─)", title="", options=["solid (─)", "dotted (┈)", "dashed (╌)"], inline ='4', group = 'RTH Gaps II---------------------------------------------')
RTH2575_line_width = input.int(2, "Width", inline ='4', group = 'RTH Gaps II---------------------------------------------')
linesToShow=input.int(3, "Historical Lines", group = 'RTH close lines & label')
show4pmLine =input.bool(false, "Previous RTH close line", inline ='2', group = 'RTH close lines & label')
show4pmLab = input.bool(false, "Price Label", inline ='2', group = 'RTH close lines & label')
extendLineRight = input.bool (false, "Extend Lines Right", inline="2", group = 'RTH close lines & label')
fourpmColor = input.color(color.new(color.silver, 10), "Line", inline ='3', group = 'RTH close lines & label')
i_RTH_line_style = input.string(defval="solid (─)", title="", options=["solid (─)", "dotted (┈)", "dashed (╌)"], inline="3", group = 'RTH close lines & label')
RTH_w = input.int(defval=3, title="Width", inline="3", group = 'RTH close lines & label')
extChoiceLine = extendLineRight?extend.right:extend.none
RTH_line_style = line_style_function(i_RTH_line_style)
RTHmid_line_style = line_style_function(i_RTHmid_line_style)
RTH2575_line_style = line_style_function(i_RTH2575_line_style)
day = math.round(hoursfwd*1000*3600)
_minute = 1000*60
fourpmCl = ta.valuewhen(time_close ==_16_15, close, 0)
var line line = na
var label lab1 =na
var line[] RTH_mid = array.new_line()
var line[] RTH_75 = array.new_line()
var line[] RTH_25 = array.new_line()
var line RTHmid_ln = na
var line RTH75_ln = na
var line RTH25_ln = na
var array<line> lineArr = array.new<line>(0)
var array<label> labelArr = array.new<label>(0)
var box bx = na
var array<box> boxArr = array.new<box>(0)
if time == _9_30 and showBox //and pre_range and disp_RTHsess
bx:=box.new(time, fourpmCl, ext_lb ? last_bar_time : time+day,open, xloc = xloc.bar_time,bgcolor = boxColor, border_color = borderColor, text =showTxt?'RTH\nGap':"", text_color = boxTxtCol, text_size = size.normal, text_valign =text.align_center, text_halign = text.align_right, border_width=border_w)
array.push(boxArr,bx)
if array.size(boxArr)>boxesToShow
box.delete(array.shift(boxArr))
RTH75 = (((fourpmCl+open)/2) + (fourpmCl))/2 //mid + top/2
RTH75_ln:=line.new(time,RTH75, ext_lb ? last_bar_time : time+day,RTH75, xloc.bar_time, color=RTh2575_cl, style=RTH2575_line_style, width=RTH2575_line_width)
if array.size(RTH_75) > boxesToShow - 1
line.delete(array.shift(RTH_75))
array.push(RTH_75, RTH75_ln)
RTH25 = (((fourpmCl+open)/2) + (open))/2 //mid + bottom/2
RTH25_ln:=line.new(time,RTH25, ext_lb ? last_bar_time : time+day,RTH25, xloc.bar_time, color=RTh2575_cl, style=RTH2575_line_style, width=RTH2575_line_width)
if array.size(RTH_25) > boxesToShow - 1
line.delete(array.shift(RTH_25))
array.push(RTH_25, RTH25_ln)
RTHmid_ln:=line.new(time,(fourpmCl+open)/2, ext_lb ? last_bar_time : time+day,(fourpmCl+open)/2, xloc.bar_time, color=RThmid_cl, style=RTHmid_line_style, width=RTHmid_line_width)
if array.size(RTH_mid) > boxesToShow - 1
line.delete(array.shift(RTH_mid))
array.push(RTH_mid, RTHmid_ln)
line:=line.new(time, fourpmCl, last_bar_time, fourpmCl, xloc=xloc.bar_time, color = show4pmLine?fourpmColor:colorNone, extend =extChoiceLine , style=RTH_line_style, width =RTH_w)
array.push(lineArr,line)
lab1:=label.new(last_bar_time,fourpmCl, str.tostring(fourpmCl), xloc=xloc.bar_time, textcolor = show4pmLab?fourpmColor:colorNone, style=label.style_label_left, color=color.new(color.black,100))
array.push(labelArr,lab1)
if array.size(lineArr)>linesToShow
line.delete(array.shift(lineArr))
if array.size(labelArr)>linesToShow
label.delete(array.shift(labelArr))
|
Multi indicators table | https://www.tradingview.com/script/EKlYtPwv/ | JuicY-trading | https://www.tradingview.com/u/JuicY-trading/ | 331 | 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/
// © JuicyWolf
//@version=5
indicator("Multi-Indicators-table", overlay = true)
//###############################################################################//
//############################### USER INPUTS ##############################//
//###############################################################################//
//############################### USER INPUTS ##############################//
//###############################################################################//
//############################### USER INPUTS ##############################//
//###############################################################################//
//############################### USER INPUTS ##############################//
//###############################################################################//
//############################### USER INPUTS ##############################//
//###############################################################################//
groupTable = "Table"
bullishColor = input.color(color.green, "bullish color", group="style")
x = 0.4
veryBullishColor = color.rgb(color.r(bullishColor)*x , color.g(bullishColor)*x, color.b(bullishColor)*x) // rend la couleur plus vive
bearishColor = input.color(color.red, "bearish color", group="style")
veryBearishColor = color.rgb(color.r(bearishColor)*x , color.g(bearishColor)*x, color.b(bearishColor)*x) // rend la couleur plus vive
neutralColor = input.color(color.gray, "neutral color", group="style")
displayTableVolatility = input.bool(true, "display volatility table", group="table parameters")
displayTableTrend = input.bool(true, "display trend table", group="table parameters")
displayTableMomentum = input.bool(true, "display momentum table", group="table parameters")
displayTableReversal = input.bool(true, "display reversal table", group="table parameters")
displayTableVolume = input.bool(true, "display volume table", group="table parameters")
displayTableRiskAssesment = input.bool(true, "display risk assessment", group="table parameters")
tablePos = input.string("Top right", "Table position", options=["Top right", "Bottom right", "Bottom left", "Top left"], group="table parameters")
tableSize = input.int(2, "Table size", maxval=5, minval=1, group="table parameters")
// Volatility indicators //
//---------//
atrLength = input.int(14, "atr length", group="volatility indicators")
bbLength = input.int(20, "bollinger bands length", group="volatility indicators")
bbSource = input.source(close, "bollinger bands source")
// Trend indicators //
//---------//
lensig = input.int(14, title="ADX Smoothing", minval=1, maxval=50, group="trend indicators")
len = input.int(14, minval=1, title="DI Length", group="trend indicators")
emaSource = input.source(close, "ema source", group="trend indicators")
ema1Length = input.int(9, "ema 1 length", group="trend indicators")
ema2Length = input.int(21, "ema 2 length", group="trend indicators")
ema3Length = input.int(50, "ema 3 length", group="trend indicators")
ema4Length = input.int(200, "ema 4 length", group="trend indicators")
superTrendLength = input(10, "supertrend length", group="trend indicators")
// Momentum indicators //
//---------//
rsiLength = input.int(14, "rsi length", group="momentum indicators")
rsiSource = input.source(close, "rsi source", group="momentum indicators")
stochLength = input.int(14, "stoch rsi length", group="momentum indicators")
mfiLength = input.int(14, "mfi length", group="momentum indicators")
mfiSource = input.source(close, "mfi source", group="momentum indicators")
williamLength = input.int(30, "wiliam %R length", group="momentum indicators")
cciLength = input.int(20, "cci length", group="momentum indicators")
cciSource = input.source(hlc3, "cci source", group="momentum indicators")
// Volume indicators //
//---------//
volumeMaLength = input.int(14, "volume ema length", group="volume indicators")
// Risk Assessment indicators //
//---------//
atrMult = input.float(title="Atr multiplicator", defval=2.5, group="risk assessment")
//###############################################################################//
//############################### REVERSAL REVERSAL ##############################//
//###############################################################################//
//############################### REVERSAL REVERSAL ##############################//
//###############################################################################//
//############################### REVERSAL REVERSAL ##############################//
//###############################################################################//
//############################### REVERSAL REVERSAL ##############################//
//###############################################################################//
//############################### REVERSAL REVERSAL ##############################//
//################################################################################//
// MACD Block //
//---------//
[macdLine, macdSignalLine, macdHistLine] = ta.macd(close, 12, 26, 9) // macdLine : bullish line, signalLine : bearish line
macdBreakup = macdLine > macdSignalLine and macdLine[1] < macdSignalLine[1]
macdBreakup2 = macdLine > macdSignalLine and macdLine[2] < macdSignalLine[2]
macdBreakup3 = macdLine > macdSignalLine and macdLine[3] < macdSignalLine[3]
macdBreakdown = macdLine < macdSignalLine and macdLine[1] > macdSignalLine[1]
macdBreakdown2 = macdLine < macdSignalLine and macdLine[2] > macdSignalLine[2]
macdBreakdown3 = macdLine < macdSignalLine and macdLine[3] > macdSignalLine[3]
macdStatus = macdBreakup or macdBreakup2 or macdBreakup3 ? "high bullish reversal risk" : macdBreakdown or macdBreakdown2 or macdBreakdown3 ? "high bearish reversal risk" : "low reversal risk"
macdColor = macdStatus == "high bullish reversal risk" ? veryBullishColor : macdStatus == "high bearish reversal risk" ? veryBearishColor : macdStatus == "bullish" ? bullishColor : macdStatus == "bearish" ? bearishColor : neutralColor
// PARABOLIC SAR BLOCK //
//---------//
parabolicSar = ta.sar(0.02, 0.02, 0.2)
psarHigherThanClose = parabolicSar > close ? true : false
breakUp = psarHigherThanClose == true and psarHigherThanClose[1] == false
breakUp2 = psarHigherThanClose == true and psarHigherThanClose[2] == false
breakUp3 = psarHigherThanClose == true and psarHigherThanClose[3] == false
breakDown = psarHigherThanClose == false and psarHigherThanClose[1] == true
breakDown2 = psarHigherThanClose == false and psarHigherThanClose[2] == true
breakDown3 = psarHigherThanClose == false and psarHigherThanClose[3] == true
psarStatus = breakUp or breakUp2 or breakUp3 ? "high bearish reversal risk": breakDown or breakDown2 or breakDown3 ? "high bullish reversal risk" : "low reversal risk"
psarColor = psarStatus == "high bearish reversal risk" ? veryBearishColor : psarStatus == "high bullish reversal risk" ? veryBullishColor : neutralColor
// PP Supertrend //
//---------//
[supertrend, direction] = ta.supertrend(3, superTrendLength)
supertrendBreakup = supertrend > close and supertrend[1] < close[1]
supertrendBreakup2 = supertrend > close and supertrend[2] < close[2]
supertrendBreakup3 = supertrend > close and supertrend[3] < close[3]
supertrendBreakdown = supertrend < close and supertrend[1] > close[1]
supertrendBreakdown2 = supertrend < close and supertrend[2] > close[2]
supertrendBreakdown3 = supertrend < close and supertrend[3] > close[3]
supertrendStatus = supertrendBreakup or supertrendBreakup2 or supertrendBreakup3 ? "high bullish reversal risk" : supertrendBreakdown or supertrendBreakdown2 or supertrendBreakdown3 ? "high bearish reversal risk" : "low reversal risk"
supertrendColor = supertrendStatus == "high bullish reversal risk" ? veryBullishColor : supertrendStatus == "high bearish reversal risk" ? veryBearishColor : supertrendStatus == "bullish" ? bullishColor : supertrendStatus == "bearish" ? bearishColor : neutralColor
//###############################################################################//
//############################### VOLATILITY VOLATILITY ##############################//
//###############################################################################//
//############################### VOLATILITY VOLATILITY ##############################//
//###############################################################################//
//############################### VOLATILITY VOLATILITY ##############################//
//###############################################################################//
//############################### VOLATILITY VOLATILITY ##############################//
//###############################################################################//
//############################### VOLATILITY VOLATILITY ##############################//
//###############################################################################//
// ATR Block //
//---------//
atr = ta.atr(atrLength)
avgArrayAtrValues = ta.ema(atr, atrLength)
atrStatus = atr < avgArrayAtrValues*0.8 ? "low volatility" : atr > avgArrayAtrValues*1.4 ? "very high volatility" : atr > avgArrayAtrValues*1.2 ? "high volatility" : "neutral"
atrColor = atrStatus == "low volatility" ? bearishColor : atrStatus == "high volatility" ? bullishColor : atrStatus == "very high volatility" ? veryBullishColor : neutralColor
// BOLLINGER Block //
//---------//
[midBollinger, upBollinger, lowBollinger] = ta.bb(bbSource, bbLength, 2)
bbEcartype = upBollinger - lowBollinger
avgArrayEcartypeValues = ta.ema(bbEcartype, bbLength)
bbEcartypeStatus = bbEcartype < avgArrayEcartypeValues*0.8 ? "low bb ecartype" : bbEcartype > avgArrayEcartypeValues*1.2 ? "high bb ecartype" : bbEcartype > avgArrayEcartypeValues*1.4 ? "very high bb ecartype" : "neutral ecartype"
[middleBB, upperBB, lowerBB] = ta.bb(close, 20, 2)
impulsedPumpColor = color.rgb(76, 175, 79, 80)
impulsedDumpColor = color.rgb(255, 82, 82, 80)
squeezeColor = color.rgb(33, 149, 243, 80)
marketPhase = close < upperBB and close > lowerBB ? "squeeze phase" : close > upperBB ? "bullish impulsion" : close < lowerBB ? "bearish impulsion" : "error"
if marketPhase[1] == "bullish impulsion"
if close > middleBB
marketPhase := "bullish impulsion"
if marketPhase[1] == "bearish impulsion"
if close < middleBB
marketPhase := "bearish impulsion"
bbPhaseColor = marketPhase == "squeeze phase" ? neutralColor : marketPhase == "bullish impulsion" ? bullishColor : marketPhase == "bearish impulsion" ? bearishColor : neutralColor
bbColor = marketPhase == "squeeze phase" and bbEcartypeStatus == "low bb ecartype" ? neutralColor : marketPhase == "bearish impulsion" ? bearishColor : marketPhase == "bullish impulsion" ? bullishColor : neutralColor
//###############################################################################//
//############################### TREND TREND TREND ##############################//
//###############################################################################//
//############################### TREND TREND TREND ##############################//
//###############################################################################//
//############################### TREND TREND TREND ##############################//
//###############################################################################//
//############################### TREND TREND TREND ##############################//
//###############################################################################//
//############################### TREND TREND TREND ##############################//
//###############################################################################//
// ADX Block //
//---------//
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)
adxMa = ta.sma(adx, 3)
adX = adxMa
adxStatus = adX > 25 ? "strong trend" : adX < 20 ? "weak trend" : "neutral trend"
adxColor = adxStatus == "strong trend" ? bullishColor : adxStatus == "weak trend" ? bearishColor : neutralColor
// SMA Block //
//---------//
sma = ta.sma(close, 20)
// EMA Block //
//---------//
ema1 = ta.ema(close, ema1Length)
ema1Status = close > ema1 ? "closed above" : "closed below"
ema2 = ta.ema(close, ema2Length)
ema2Status = close > ema2 ? "closed above" : "closed below"
ema3 = ta.ema(close, ema3Length)
ema3Status = close > ema3 ? "closed above" : "closed below"
ema4 = ta.ema(close, ema4Length)
ema4Status = close > ema4 ? "closed above" : "closed below"
emaAboveCount = 0
emaAboveCount += ema1Status == "closed above" ? 1 : 0
emaAboveCount += ema2Status == "closed above" ? 1 : 0
emaAboveCount += ema3Status == "closed above" ? 1 : 0
emaAboveCount += ema4Status == "closed above" ? 1 : 0
emaColor = emaAboveCount > 3 ? veryBullishColor : emaAboveCount > 2 ? bullishColor : emaAboveCount < 1 ? veryBearishColor : emaAboveCount < 2 ? bearishColor : neutralColor
emaStatus = emaAboveCount > 3 ? "very bullish" : emaAboveCount > 2 ? "bullish" : emaAboveCount < 1 ? "very bearish" : emaAboveCount < 2 ? "bearish" : "neutral"
// AROON Block //
//---------//
aroonUpper = 100 * (ta.highestbars(high, 14) + 14)/14
aroonLower = 100 * (ta.lowestbars(low, 14) + 14)/14
aroonStatus = aroonUpper > 50 and aroonLower < 50 ? "bullish trend" : aroonLower > 50 and aroonUpper < 50 ? "bearish trend" : "neutral trend"
aroonColor = aroonStatus == "bullish trend" ? bullishColor : aroonStatus == "bearish trend" ? bearishColor : neutralColor
// PSAR Block //
//---------//
psarTrendStatus = parabolicSar < close ? "bullish trend" : "bearish trend"
psartrendColor = psarTrendStatus == "bullish trend" ? bullishColor : bearishColor
// Supertrend Block //
//---------//
superTrendStatus = supertrend < close ? "bullish trend" : "bearish trend"
superTrendColor = superTrendStatus == "bullish trend" ? bullishColor : bearishColor
//###############################################################################//
//############################### MOMENTUM MOMENTUM ##############################//
//###############################################################################//
//############################### MOMENTUM MOMENTUM ##############################//
//###############################################################################//
//############################### MOMENTUM MOMENTUM ##############################//
//###############################################################################//
//############################### MOMENTUM MOMENTUM ##############################//
//###############################################################################//
//############################### MOMENTUM MOMENTUM ##############################//
//###############################################################################//
// RSI Block //
//---------//
rsi = ta.rsi(source = rsiSource, length = rsiLength )
rsiStatus = rsi > 85 ? "very overbought" : rsi > 70 ? "overbought" : rsi < 15 ? "very oversold" : rsi < 30 ? "oversold" : "neutral"
rsiColor = rsiStatus == "very overbought" ? veryBearishColor : rsiStatus == "overbought" ? bearishColor : rsiStatus == "very oversold" ? veryBullishColor : rsiStatus == "oversold" ? bullishColor : neutralColor
// STOCH RSI Block //
//---------//
k = ta.sma(ta.stoch(rsi, rsi, rsi, stochLength), 3)
stochasticRsi = ta.sma(k, 3)
stochasticRsiStatus = stochasticRsi > 90 ? "very overbought" : stochasticRsi > 80 ? "overbought" : stochasticRsi < 10 ? "very oversold" : stochasticRsi < 20 ? "oversold" : "neutral"
stochasticRsiColor = stochasticRsiStatus == "very overbought" ? veryBearishColor : stochasticRsiStatus == "overbought" ? bearishColor : stochasticRsiStatus == "very oversold" ? veryBullishColor : stochasticRsiStatus == "oversold" ? bullishColor : neutralColor
// MFI Block //
//---------//
mfi = ta.mfi(mfiSource, mfiLength) // money flow index
mfiStatus = mfi > 90 ? "very overbought" : mfi > 80 ? "overbought" : mfi < 10 ? "very oversold" : mfi < 20 ? "oversold" : "neutral"
mfiColor = mfiStatus == "very overbought" ? veryBearishColor : mfiStatus == "overbought" ? bearishColor : mfiStatus == "very oversold" ? veryBullishColor : mfiStatus == "oversold" ? bullishColor : neutralColor
// WILLIAM %R Block //
//---------//
williamVixFormula = 100 * (close - ta.highest(williamLength)) / (ta.highest(williamLength) - ta.lowest(williamLength))
wvxStatus = williamVixFormula > -20 ? "bearish" : williamVixFormula < -80 ? "bullish" : "neutral"
wvxColor = wvxStatus == "bearish" ? bearishColor: wvxStatus == "bullish" ? bullishColor : neutralColor
// CCI Block //
//---------//
cci = ta.cci(cciSource, cciLength)
cciStatus = cci > 200 ? "very overbought" : cci > 100 ? "overbought" : cci < -200 ? "very oversold" : cci < -100 ? "oversold" : "neutral"
cciColor = cciStatus == "very overbought" ? veryBearishColor : cciStatus == "overbought" ? bearishColor : cciStatus == "oversold" ? bullishColor : cciStatus == "very oversold" ? veryBullishColor : neutralColor
// STOCH Block //
//---------//
stoch = ta.stoch(close, high, low, 14)
stochStatus = stoch > 80 ? "overbought" : stoch < 20 ? "oversold" : "neutral"
stochColor = stochStatus == "overbought" ? bearishColor : stochStatus == "oversold" ? bullishColor : neutralColor
// MOMENTUM Block //
//---------//
mom = ta.mom(source = close, length = 10)
//###############################################################################//
//############################### VOLUME VOLUME ##############################//
//###############################################################################//
//############################### VOLUME VOLUME ##############################//
//###############################################################################//
//############################### VOLUME VOLUME ##############################//
//###############################################################################//
//############################### VOLUME VOLUME ##############################//
//###############################################################################//
//############################### VOLUME VOLUME ##############################//
//###############################################################################//
// Volume compared to avgVolume Block //
//---------//
avgArrayVolumeValues = ta.ema(volume, volumeMaLength)
volumeStatus = volume > avgArrayVolumeValues*1.8 ? "very high volume" : volume > avgArrayVolumeValues*1.4 ? "high volume" : volume < avgArrayVolumeValues*0.6 ? "very low volume" : volume < avgArrayVolumeValues*0.8 ? "low volume" : "normal volume"
colorVolume = volumeStatus == "very high volume" ? veryBullishColor : volumeStatus == "high volume" ? bullishColor : volumeStatus == "very low volume" ? bearishColor : volumeStatus == "low volume" ? bearishColor: neutralColor
//###############################################################################//
//############################### RISK ASSESSMENT ##############################//
//###############################################################################//
//############################### RISK ASSESSMENT ##############################//
//###############################################################################//
//############################### RISK ASSESSMENT ##############################//
//###############################################################################//
//############################### RISK ASSESSMENT ##############################//
//###############################################################################//
//############################### RISK ASSESSMENT ##############################//
//###############################################################################//
slLong = ta.highest(high, 3) + atr * atrMult
slShort = ta.lowest(low, 3) - atr * atrMult
ph = ta.pivothigh(10, 10)
pl = ta.pivotlow(10, 10)
length = 14
// Calculate the difference between the last 10 pivot highs and pivot lows
var phTotal = array.new_float(length)
var plTotal = array.new_float(length)
for i = 0 to length - 1
array.push(phTotal, ph[i])
array.push(plTotal, pl[i])
avgPriceMovement = array.avg(phTotal) - array.avg(plTotal)
avgPriceMovement := ta.ema(avgPriceMovement, 9)
avgPriceMovementPercent = (avgPriceMovement/close)*100
maxLeverage = 100 / avgPriceMovementPercent
maxLeverage := maxLeverage*0.8 // Ensuring a bit more of safety
if maxLeverage < 1
maxLeverage := 1
//###############################################################################//
//############################### FRONT END ##############################//
//###############################################################################//
//############################### FRONT END ##############################//
//###############################################################################//
//############################### FRONT END ##############################//
//###############################################################################//
//############################### FRONT END ##############################//
//###############################################################################//
//############################### FRONT END ##############################//
//###############################################################################//
//Table position and size
tablePosition = tablePos == "Top right" ? position.top_right : tablePos == "Bottom right" ? position.bottom_right : tablePos == "Bottom left" ? position.bottom_left : position.top_left
tableTextSize = tableSize == 1 ? size.tiny : tableSize == 2 ? size.small : tableSize == 3 ? size.normal : tableSize == 4 ? size.huge : size.large
tableTitleTextSize = tableSize == 1 ? size.small : tableSize == 2 ? size.normal : size.normal
var metricTable = table.new(position = tablePosition, columns = 50, rows = 50, bgcolor = color.new(color.black, 80), border_width = 3, border_color=color.rgb(23, 23, 23))
n = "\n"
colorRow1 = color.blue
//Populating table
if displayTableVolatility
table.cell(table_id = metricTable, column = 1, row = 1, text = "Volatility" + n + "⎯⎯⎯⎯⎯⎯⎯⎯" + n + "Value" + n + "⎯⎯⎯⎯⎯⎯" + n + "Status", text_color=colorRow1, text_halign = text.align_left, text_size=tableTextSize)
table.cell(table_id = metricTable, column = 2, row = 1, text = "ATR" + n + "⎯⎯⎯⎯" + n + str.tostring(math.round(atr)) + " : " + str.tostring(math.round((atr/close)*100, 2)) + "%" + n + "⎯⎯⎯⎯" + n + atrStatus, text_color=color.white, text_halign = text.align_center, bgcolor=atrColor, text_size=tableTextSize)
table.cell(table_id = metricTable, column = 3, row = 1, text = "Bollinger Bands" + n + "⎯⎯⎯⎯" + n + bbEcartypeStatus + " : " + str.tostring(math.round((bbEcartype/close)*100, 2)) + "%" + n + "⎯⎯⎯⎯" + n + "bb phase" + " : " + marketPhase, text_color=color.white, text_halign = text.align_center, bgcolor=bbColor, text_size=tableTextSize)
if displayTableReversal
table.cell(table_id = metricTable, column = 1, row = 4, text = "Reversal" + n + "⎯⎯⎯⎯⎯⎯⎯⎯" + n + "Value" + n + "⎯⎯⎯⎯⎯⎯" + n + "Status", text_color=colorRow1, text_halign = text.align_left, text_size=tableTextSize)
table.cell(table_id = metricTable, column = 2, row = 4, text = "PSAR" + n + "⎯⎯⎯⎯" + n + str.tostring(math.round(parabolicSar)) + n + "⎯⎯⎯⎯" + n + psarStatus, text_color=color.white, text_halign = text.align_center, bgcolor=psarColor, text_size=tableTextSize)
table.cell(table_id = metricTable, column = 3, row = 4, text = "MACD" + n + "⎯⎯⎯⎯" + n + str.tostring(math.round(macdLine)) + n + "⎯⎯⎯⎯" + n + macdStatus, text_color=color.white, text_halign = text.align_center, bgcolor=macdColor, text_size=tableTextSize)
table.cell(table_id = metricTable, column = 4, row = 4, text = "Super Trend" + n + "⎯⎯⎯⎯" + n + str.tostring(math.round(supertrend)) + n + "⎯⎯⎯⎯" + n + supertrendStatus, text_color=color.white, text_halign = text.align_center, bgcolor=supertrendColor, text_size=tableTextSize)
if displayTableTrend
table.cell(table_id = metricTable, column = 1, row = 2, text = "Trend" + n + "⎯⎯⎯⎯⎯⎯⎯⎯" + n + "Value" + n + "⎯⎯⎯⎯⎯⎯" + n + "Status", text_color=colorRow1, text_halign = text.align_left, text_size=tableTextSize)
table.cell(table_id = metricTable, column = 2, row = 2, text = "ADX" + n + "⎯⎯⎯⎯" + n + str.tostring(math.round(adX)) + n + "⎯⎯⎯⎯" + n + adxStatus, text_color=color.white, text_halign = text.align_center, bgcolor=adxColor, text_size=tableTextSize)
table.cell(table_id = metricTable, column = 3, row = 2, text = "EMA" + n + "⎯⎯⎯⎯" + n + str.tostring(ema1Length) + " : "+ str.tostring(ema1Status) + n + "⎯⎯⎯⎯" + n + str.tostring(ema2Length) + " : "+ str.tostring(ema2Status) + n + "⎯⎯⎯⎯" + n + str.tostring(ema3Length) + " : "+ str.tostring(ema3Status) + n + "⎯⎯⎯⎯" + n + str.tostring(ema4Length) + " : "+ str.tostring(ema4Status) + n + "⎯⎯⎯⎯" + n + emaStatus + " trend", text_color=color.white, text_halign = text.align_center, bgcolor=emaColor, text_size=tableTextSize)
table.cell(table_id = metricTable, column = 4, row = 2, text = "Aroon" + n + "⎯⎯⎯⎯" + n + aroonStatus, text_color=color.white, text_halign = text.align_center, bgcolor=aroonColor, text_size=tableTextSize)
table.cell(table_id = metricTable, column = 5, row = 2, text = "PSAR" + n + "⎯⎯⎯⎯" + n + str.tostring(math.round(parabolicSar)) + n + "⎯⎯⎯⎯" + n + psarTrendStatus, text_color=color.white, text_halign = text.align_center, bgcolor=psartrendColor, text_size=tableTextSize)
table.cell(table_id = metricTable, column = 6, row = 2, text = "Super Trend" + n + "⎯⎯⎯⎯" + n + str.tostring(math.round(supertrend)) + n + "⎯⎯⎯⎯" + n + superTrendStatus, text_color=color.white, text_halign = text.align_center, bgcolor=superTrendColor, text_size=tableTextSize)
if displayTableMomentum
table.cell(table_id = metricTable, column = 1, row = 3, text = "Momentum" + n + "⎯⎯⎯⎯⎯⎯⎯⎯" + n + "Value" + n + "⎯⎯⎯⎯⎯⎯" + n + "Status", text_color=colorRow1, text_halign = text.align_left, text_size=tableTextSize)
table.cell(table_id = metricTable, column = 2, row = 3, text = "StochRSI" + n + "⎯⎯⎯⎯" + n + str.tostring(math.round((stochasticRsi))) + n + "⎯⎯⎯⎯" + n + stochasticRsiStatus, text_color=color.white, text_halign = text.align_center, bgcolor=stochasticRsiColor, text_size=tableTextSize)
table.cell(table_id = metricTable, column = 3, row = 3, text = "MFI" + n + "⎯⎯⎯⎯" + n + str.tostring(math.round((mfi))) + n + "⎯⎯⎯⎯" + n + mfiStatus, text_color=color.white, text_halign = text.align_center, bgcolor=mfiColor, text_size=tableTextSize)
table.cell(table_id = metricTable, column = 4, row = 3, text = "William %R" + n + "⎯⎯⎯⎯" + n + str.tostring(math.round((williamVixFormula))) + n + "⎯⎯⎯⎯" + n + wvxStatus, text_color=color.white, text_halign = text.align_center, bgcolor=wvxColor, text_size=tableTextSize)
table.cell(table_id = metricTable, column = 5, row = 3, text = "RSI" + n + "⎯⎯⎯⎯" + n + str.tostring(math.round(rsi)) + n + "⎯⎯⎯⎯" + n + rsiStatus, text_color=color.white, text_halign = text.align_center, bgcolor=rsiColor, text_size=tableTextSize)
table.cell(table_id = metricTable, column = 6, row = 3, text = "CCI" + n + "⎯⎯⎯⎯" + n + str.tostring(math.round(cci)) + n + "⎯⎯⎯⎯" + n + cciStatus, text_color=color.white, text_halign = text.align_center, bgcolor=cciColor, text_size=tableTextSize)
if displayTableVolume
table.cell(table_id = metricTable, column = 1, row = 5, text = "Volume" + n + "⎯⎯⎯⎯⎯⎯⎯⎯" + n + "Value" + n + "⎯⎯⎯⎯⎯⎯" + n + "Status", text_color=colorRow1, text_halign = text.align_left, text_size=tableTextSize)
table.cell(table_id = metricTable, column = 2, row = 5, text = "Volume EMA" + n + "⎯⎯⎯⎯" + n + str.tostring(math.round((volume))) + n + "⎯⎯⎯⎯" + n + volumeStatus, text_color=color.white, text_halign = text.align_center, bgcolor=colorVolume, text_size=tableTextSize)
if displayTableRiskAssesment
table.cell(table_id = metricTable, column = 1, row = 6, text = "Risk" + n + "Assessment", text_color=color.blue, text_halign = text.align_left, text_size=tableTextSize)
table.cell(table_id = metricTable, column = 2, row = 6, text = "Max Leverage" + n + "⎯⎯⎯⎯" + n + str.tostring(math.round(maxLeverage, 1)), text_color=color.white, text_halign = text.align_center, bgcolor=color.new(color.blue, 80), text_size=tableTextSize)
table.cell(table_id = metricTable, column = 3, row = 6, text = "ATR Stop Loss" + n + "⎯⎯⎯⎯" + n + "Long SL: " + str.tostring(math.round(slLong, 2)) + n + "⎯⎯⎯⎯" + n + "Short SL: " + str.tostring(math.round(slShort, 2)), text_color=color.white, text_halign = text.align_center, bgcolor=color.new(color.blue, 80), text_size=tableTextSize)
|
ICT Liquidty H/L [MK] | https://www.tradingview.com/script/qQd5z3L9-ICT-Liquidty-H-L-MK/ | malk1903 | https://www.tradingview.com/u/malk1903/ | 419 | 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/
//@malk1903
//@version=5
indicator(title='ICT Liquidty H/L [MK]', shorttitle = 'ICT Liquidty H/L [MK]',overlay=true, max_boxes_count = 500, max_labels_count = 500)
plotLiq = input.bool(defval=true, title='Liquidity Highs/Lows', group='Enable/Disable Section---------------------------------------------', inline = '01')
/////////////////////////////////////////////////////////////////////////Liquidity Equal Highs
pvtTopColor = input.color(defval=color.new(color.green,85), title='Top Color', group='Liquidity-------------------------------------------------', inline='1')
pvtBtmColor = input.color(defval=color.new(color.red,85), title='Bottom Color', group='Liquidity-------------------------------------------------',inline = '1')
pvtStyle = line.style_solid
pvtMax = input.int(defval=30, title='Maximum Liquidity Displayed', minval=1, maxval=500, group='Liquidity-------------------------------------------------', tooltip='Minimum = 1, Maximum = 500')
delline = input.bool(defval=true, title='Delete After X Bars Through Line', group='Liquidity-------------------------------------------------')
mitdel = input.int(defval=15, title='Mitigated+Line Delete (X Bars)', minval=1, maxval=100, group='Liquidity-------------------------------------------------', tooltip='Line will remain on chart until this many bars after first broken through. Minimum = 1, Maximum = 500')
linebrk = input.bool(defval=true, title='Color After Close Through Line', group='Liquidity-------------------------------------------------')
mitdelcol = input.color(defval=(color.new(#34eb40,0)), title='Mitigated Color', group='Liquidity-------------------------------------------------', tooltip = 'Once broken, line will change to this colour until deleted. Line deletion is controlled by (Mitigated+Line Delete) input control')
//del_pc = input.bool(defval=false, title='', group='Liquidity-------------------------------------------------', inline="m")
//mitdel_pc = input.int(defval=300, title='Only show lines within x% of current price', minval=1, maxval=500, step=50, group='Liquidity-------------------------------------------------', inline="m")
//
brkstyle = line.style_dashed
var line[] _lowLiqLines = array.new_line()
var line[] _highLiqLines = array.new_line()
//Functions
isPvtHigh(_index, __high) =>
__high[_index+2] < __high[_index+1] and __high[_index+1] > __high[_index]
// | <-- pivot high
// ||| <-- candles
// 210 <-- candle index
isPvtLow(_index, __low) =>
__low[_index+2] > __low[_index+1] and __low[_index+1] < __low[_index]
// ||| <-- candles
// | <-- pivot low
// 210 <-- candle index
//Function to Calculte Line Length
_controlLine(_lines, __high, __low) =>
if array.size(_lines) > 0
for i = array.size(_lines) - 1 to 0 by 1
_line = array.get(_lines, i)
_lineLow = line.get_y1(_line)
_lineHigh = line.get_y2(_line)
_lineRight = line.get_x2(_line)
if na or (bar_index == _lineRight and not((__high > _lineLow and __low < _lineLow) or (__high > _lineHigh and __low < _lineHigh)))
line.set_x2(_line, bar_index + 1)
//deletes line if not within X% of current last price
//pch = (mitdel_pc/100) + 1
//pcl = 1 - (mitdel_pc/100)
//cprice = close
//highpc = (cprice * pch)
//lowpc = (cprice * pcl)
//if del_pc
//if _lineLow < close + mitdel_pc //) and > (close*0.98)) //if Y2 < close*1.05
//line.set_color(_line, color.new(color.white,50))
//line.delete(_line)
///deletes line if more than X bars pass through
if _lineRight > bar_index[mitdel] and _lineRight < bar_index[0] and linebrk
line.set_color(_line,mitdelcol)
line.set_style(_line, brkstyle)
if _lineRight < bar_index[mitdel] and delline
line.delete(_line)
//Pivot Low Line Plotting
if isPvtLow(0, low) and plotLiq
_lowPVT = line.new(x1=bar_index - 1, y1=low[1], x2=bar_index, y2=low[1], extend=extend.none, color=pvtBtmColor, style=pvtStyle)
if array.size(_lowLiqLines) >= pvtMax
line.delete(array.shift(_lowLiqLines))
array.push(_lowLiqLines, _lowPVT)
//Pivot High Line Plotting
if isPvtHigh(0, high) and plotLiq
_highPVT = line.new(x1=bar_index - 1, y1=high[1], x2=bar_index, y2=high[1], extend=extend.none, color=pvtTopColor, style=pvtStyle)
if array.size(_highLiqLines) >= pvtMax
line.delete(array.shift(_highLiqLines))
array.push(_highLiqLines, _highPVT)
if plotLiq
_controlLine(_lowLiqLines, high, low)
_controlLine(_highLiqLines, high, low) |
Premium Linear Regression - The Quant Science | https://www.tradingview.com/script/WOhBM8Va-Premium-Linear-Regression-The-Quant-Science/ | thequantscience | https://www.tradingview.com/u/thequantscience/ | 348 | 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/
// © thequantscience
// ██████╗ ██████╗ ███████╗███╗ ███╗██╗██╗ ██╗███╗ ███╗ ██╗ ██╗███╗ ██╗███████╗ █████╗ ██████╗ ██████╗ ███████╗ ██████╗
// ██╔══██╗██╔══██╗██╔════╝████╗ ████║██║██║ ██║████╗ ████║ ██║ ██║████╗ ██║██╔════╝██╔══██╗██╔══██╗ ██╔══██╗██╔════╝██╔════╝
// ██████╔╝██████╔╝█████╗ ██╔████╔██║██║██║ ██║██╔████╔██║ ██║ ██║██╔██╗ ██║█████╗ ███████║██████╔╝ ██████╔╝█████╗ ██║ ███╗
// ██╔═══╝ ██╔══██╗██╔══╝ ██║╚██╔╝██║██║██║ ██║██║╚██╔╝██║ ██║ ██║██║╚██╗██║██╔══╝ ██╔══██║██╔══██╗ ██╔══██╗██╔══╝ ██║ ██║
// ██║ ██║ ██║███████╗██║ ╚═╝ ██║██║╚██████╔╝██║ ╚═╝ ██║ ███████╗██║██║ ╚████║███████╗██║ ██║██║ ██║ ██║ ██║███████╗╚██████╔╝
// ╚═╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚══════╝╚═╝╚═╝ ╚═══╝╚══════╝╚═╝ ╚═╝╚═╝ ╚═╝ ╚═╝ ╚═╝╚══════╝ ╚═════╝
//@version=5
indicator("Premium Linear Regression - The Quant Science", overlay = true)
// ################################################################################################################################################
startDate = input.int(title="Date: ", defval=1, minval=1, maxval=31, inline = 'Start', group = "START DATE PERIOD")
startMonth = input.int(title="Month: ", defval=1, minval=1, maxval=12, inline = 'Start', group = "START DATE PERIOD")
startYear = input.int(title="Year: ", defval=2018, minval=1800, maxval=2100, inline = 'Start', group = "START DATE PERIOD")
// ################################################################################################################################################
endDate = input.int(title="Date: ", defval=31, minval=1, maxval=31, inline = 'End', group = "END DATE PERIOD")
endMonth = input.int(title="Month: ", defval=12, minval=1, maxval=12, inline = 'End', group = "END DATE PERIOD")
endYear = input.int(title="Year: ", defval=2023, minval=1800, maxval=2100, inline = 'End', group = "END DATE PERIOD")
// ################################################################################################################################################
inDateRange = (time >= timestamp(syminfo.timezone, startYear, startMonth, startDate, 0, 0)) and (time < timestamp(syminfo.timezone, endYear, endMonth, endDate, 0, 0))
// ################################################################################################################################################
len = input.int(200, minval=1, title="Length:", inline = "s", group = "Lenght & Source")
src = input.source(close, title="Source:", inline = "s", group = "Lenght & Source")
// ################################################################################################################################################
out_linreg = ta.linreg(src, len, 0)
tf_linreg = input.timeframe(title="Timeframe:", defval="1D", group = "Timeframe Configuration")
// ################################################################################################################################################
colorlinreg1 = input.color(defval = #00ff00, inline = "x", title = "Up:", group = "COLOR CONFIGURATION")
colorlinreg2 = input.color(defval = #ff0000 , inline = "x", title = "Down:", group = "COLOR CONFIGURATION")
colorlinreg3 = input.color(defval = color.rgb(231, 231, 231, 98), inline = "y", title = "Background:", group = "COLOR CONFIGURATION")
// ################################################################################################################################################
linreg = request.security(syminfo.tickerid, tf_linreg, out_linreg, gaps=barmerge.gaps_on)
// ################################################################################################################################################
var float close_up = 0
var float close_down = 0
var float storage_up = 0
var float storage_down = 0
var int count_up = 0
var int count_down = 0
if close > linreg and inDateRange
close_up := close - linreg
storage_up += close_up
count_up += 1
if close < linreg and inDateRange
close_down := linreg - close
storage_down += close_down
count_down += 1
avg_up = storage_up / count_up
avg_down = storage_down / count_down
checkingline_up = linreg + avg_up
checkingline_down = linreg - avg_down
// ################################################################################################################################################
colorgreen = linreg <= close
colorred = linreg >= close
linreg_color = colorred ? #ff0000 : colorgreen ? #00ff00 : na
plot(linreg, color = linreg_color, linewidth = 2)
plot(checkingline_up, color = colorlinreg1, style = plot.style_circles)
plot(checkingline_down, color = colorlinreg2, style = plot.style_circles)
// ################################################################################################################################################
|
RSIOMA with Volume Index Confirmation | https://www.tradingview.com/script/TNvXmirg-RSIOMA-with-Volume-Index-Confirmation/ | BoredDev | https://www.tradingview.com/u/BoredDev/ | 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/
// © BoredDev
//@version=5
indicator("RSIOMA with Volume Index Confirmation", overlay=true)
// Input parameters
rsi_length = input.int(14, title="RSI Length", minval=1)
rsi_ob_level = input.int(70, title="Overbought Level")
rsi_os_level = input.int(30, title="Oversold Level")
nvi_length = input.int(255, title="NVI Length")
pvi_length = input.int(255, title="PVI Length")
// RSI calculation
rsi = ta.rsi(close, rsi_length)
// NVI calculation
nvi = 1.0
for i = 1 to nvi_length
if volume[i] < volume[i-1]
nvi := nvi + (nz(close[i], close[i-1]) - nz(close[i-1], close[i])) / nz(close[i-1], close[i])
else
nvi := nvi
// PVI calculation
pvi = 1.0
for i = 1 to pvi_length
if volume[i] > volume[i-1]
pvi := pvi + (nz(close[i], close[i-1]) - nz(close[i-1], close[i])) / nz(close[i-1], close[i])
else
pvi := pvi
// Determine entry points
bearish_div = (ta.rsi(close, rsi_length)[1] > rsi_ob_level) and (rsi < rsi_ob_level) and (close[1] > close)
bullish_div = (ta.rsi(close, rsi_length)[1] < rsi_os_level) and (rsi > rsi_os_level) and (close[1] < close)
sell_signal = bearish_div and nvi < nz(nvi[1], 1.0)
buy_signal = bullish_div and pvi > nz(pvi[1], 1.0)
// Plot signals
plotshape(sell_signal, title="Sell", style=shape.triangledown, location=location.abovebar, color=color.red)
plotshape(buy_signal, title="Buy", style=shape.triangleup, location=location.belowbar, color=color.green)
|
PBoC Liquidity Injections [tedtalksmacro] | https://www.tradingview.com/script/wb5kFP4E-PBoC-Liquidity-Injections-tedtalksmacro/ | tedtalksmacro | https://www.tradingview.com/u/tedtalksmacro/ | 410 | 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/
// © tedtalksmacro
//@version=5
indicator("PBoC Liquidity Injections [tedtalksmacro]", overlay = false, format = format.price)
// Calculate Chinese Liquidity
chinarrpclose = request.security("CNLIVRR * FX_IDC:CNYUSD", "D", close, currency = currency.USD)
chinamlfclose = request.security("CNLIVMLF * FX_IDC:CNYUSD", "D", close, currency = currency.USD)
totalliquidity = chinamlfclose + chinarrpclose
// plot liquidity
plot(totalliquidity / 1000000000, style = plot.style_columns, linewidth=2, color= color.rgb(4, 4, 4), title = 'Total Injections [bn USD]')
plot(chinamlfclose / 1000000000, style = plot.style_columns, linewidth=2, color= color.rgb(60, 79, 126), title = 'MLF Injections [bn USD]')
plot(chinarrpclose / 1000000000, style = plot.style_columns, linewidth=2, color= color.rgb(255, 165, 0), title = 'Reverse Repo [bn USD]')
|
Weighted Bollinger Band (+ Logarithmic) | https://www.tradingview.com/script/w42rViaI-Weighted-Bollinger-Band-Logarithmic/ | Dicargo_Beam | https://www.tradingview.com/u/Dicargo_Beam/ | 56 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Dicargo_Beam
//@version=5
indicator("Weighted Bollinger Band (+ Logarithmic)", overlay=true)
length = input.int(20, minval=1)
_src = input(close, title="Source")
mult = input.float(2.0, minval=0.001, maxval=50, title="Mult")
Type = input.string("Logarithmic", "Weighted BB type", options = ["Standard", "Logarithmic"])
float src = switch Type
"Logarithmic" => math.log10(_src)
=> _src
_basis = ta.wma(src, length)
weighted_stdev(src, length) =>
sumOfSquareDeviations = 0.0
norm = 0.0
for i = 0 to length - 1
sum = src[i] - _basis
w = length - i
norm := norm + w
sumOfSquareDeviations := sumOfSquareDeviations + sum * sum * w
stdev = math.sqrt(sumOfSquareDeviations / norm)
dev = mult * weighted_stdev(src, length)
[basis, upper, lower] = switch Type
"Logarithmic" => [math.pow(10,_basis), math.pow(10,_basis + dev), math.pow(10,_basis - dev)]
=> [_basis, _basis + dev, _basis - dev]
plot(basis, "Basis", color=#FF6D00)
p1 = plot(upper, "Upper", color=#29bbff)
p2 = plot(lower, "Lower", color=#29bbff)
fill(p1, p2, title = "Background", color=color.rgb(33, 124, 243, 90))
|
Volume Based Support & Resistance | https://www.tradingview.com/script/56EVB7Xr-Volume-Based-Support-Resistance/ | NoaTrader | https://www.tradingview.com/u/NoaTrader/ | 147 | 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/
// © noafarin
//@version=5
indicator("Volume Based Support & Resistance","VBSR",overlay = true,max_lines_count =500,max_labels_count = 500)
var sr_diff_input = input.float(10,"Major Supp/Res Lines difference %",tooltip = "Major S/R Lines percent difference",group = "Easy Settings")
var variable_line_distance_from_main = input.float(0.382,"Variable S/R Distance From Main",group = "Pro Settings") // 1 - 0.618
var variable_line_distance_from_eachother = input.float(0.236,"Variable S/R Distance From Eachother",group = "Pro Settings") // 0.618 - 0.382
var len = input.int(52,"Volume Hgihest Length",tooltip = "Number of candles for lookback of the highest function",group = "Volume Settings")
var devider = input.float(0.5,"Volume Devider",tooltip = "highest(volume,len) * devider ",group = "Volume Settings")
var show_variable_line_change_point_label = input.bool(false,"Show variable lines change point label",group = "Labels (Debug)")
var show_lines_nuber_label = input.bool(false,"Show lines number label",group = "Labels (Debug)")
var show_diff_input = sr_diff_input * 2
var line_array = array.new_line()
var variable_line_array = array.new_line()
var sr_prices = array.new_float()
var major_sr_prices = array.new_float()
var major_cross_counter = 0
compare_src = hlcc4 //input(hlcc4)
vol_src = volume
the_price = close
if close > open // green
if close[1] < open[1] // red
the_price := low // pull back
else
the_price := high // reverse
else // red
if close[1] < open[1] // throw back
the_price := low
else
the_price := high
contrast_color = chart.bg_color == color.white ? color.yellow : color.orange
vol_cond = vol_src > ta.highest(vol_src,len) * devider
if vol_cond
if array.size(line_array) == 0
array.push(line_array,line.new(bar_index,the_price,bar_index+10,the_price))
else
is_sr_new = true
for i = 0 to array.size(line_array) - 1
the_line = array.get(line_array,i)
the_lines_price = line.get_y1(the_line)
the_difference = math.abs(the_lines_price - the_price) * 100 / the_price
if the_difference < sr_diff_input // there is a line near previous lines
//method 3
if the_difference > sr_diff_input * variable_line_distance_from_main and the_difference < sr_diff_input * (1-variable_line_distance_from_main)
if array.size(variable_line_array) == 0
array.push(variable_line_array,line.new(bar_index,the_price,bar_index+90,the_price,color = color.purple))
else
is_var_sr_new = true
for j = 0 to array.size(variable_line_array) - 1
the_var_line = array.get(variable_line_array,j)
the_var_lines_price = line.get_y1(the_var_line)
the_var_difference = math.abs(the_var_lines_price - the_price) * 100 / the_price
if the_var_difference < sr_diff_input * variable_line_distance_from_eachother
line.set_y1(the_var_line,the_price)
line.set_y2(the_var_line,the_price)
line.set_x2(the_var_line,bar_index)
line.set_color(the_var_line,contrast_color)
sr_i = array.binary_search(sr_prices,the_var_lines_price)
if sr_i != -1
array.set(sr_prices,sr_i,the_price)
if show_variable_line_change_point_label
label.new(bar_index,high)
is_var_sr_new := false
break
if is_var_sr_new
array.push(variable_line_array,line.new(bar_index,the_price,bar_index+90,the_price,color = color.purple))
is_sr_new := false
break
if is_sr_new
array.push(line_array,line.new(bar_index,the_price,bar_index+10,the_price))
// majors
for i = 0 to array.size(line_array)? array.size(line_array) - 1 : na
the_line = array.get(line_array,i)
the_lines_price = line.get_y1(the_line)
line.set_color(the_line,close > the_lines_price?color.green:color.red)
if math.abs((the_lines_price - compare_src)) * 100 / compare_src > show_diff_input
line.set_extend(the_line,extend.none)
line.set_style(the_line,line.style_dashed)
line.set_color(the_line,color=color.blue)
else
line.set_style(the_line,line.style_solid)
if math.abs((the_lines_price - high)) * 100 / high < sr_diff_input or math.abs((the_lines_price - low)) * 100 / low < sr_diff_input
line.set_x2(the_line,bar_index)
if array.size(sr_prices) == 0 or not array.includes(sr_prices,the_lines_price)
array.push(sr_prices,the_lines_price)
if array.size(major_sr_prices) == 0 or not array.includes(major_sr_prices,the_lines_price)
array.push(major_sr_prices,the_lines_price)
// minors
for j = 0 to array.size(variable_line_array) ? array.size(variable_line_array) - 1 : na
the_line = array.get(variable_line_array,j)
the_lines_price = line.get_y1(the_line)
line.set_color(the_line,contrast_color)
line.set_style(the_line,line.style_dashed)
if math.abs((the_lines_price - high)) * 100 / high < sr_diff_input or math.abs((the_lines_price - low)) * 100 / low < sr_diff_input * variable_line_distance_from_eachother
line.set_x2(the_line,bar_index)
if array.size(sr_prices) == 0 or not array.includes(sr_prices,the_lines_price)
array.push(sr_prices,the_lines_price)
array.sort(sr_prices)
if bar_index == last_bar_index and show_lines_nuber_label
label.new(bar_index+10,high,str.tostring(array.size(line_array))+" main lines\n" + str.tostring(array.size(variable_line_array)) + " var lines\n" + str.tostring(array.size(sr_prices)) + " all\n" + str.tostring(array.size(major_sr_prices)) + " majors" ,textcolor = color.white)
|
ORB Smart Candle finder [With Volume Candle] with EXTEND | https://www.tradingview.com/script/2kwsy28Y-ORB-Smart-Candle-finder-With-Volume-Candle-with-EXTEND/ | Papadaulat | https://www.tradingview.com/u/Papadaulat/ | 68 | 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/
// © Papadaulat
//@version=5
indicator(title="ORB Smart Candle finder [With Volume Candle] with EXTEND", overlay=true, precision=0, format=format.volume)
InSession(sessionTimesZ) =>
not na(time(timeframe.period, sessionTimesZ))
barsize = input(40, title = "Candle Size" )
highbar1 = open
lowbar1 = close
sessionTime = input.session("0915-1045", title="Time")
barvalue = math.abs(highbar1 - lowbar1)
candlerange = barvalue < barsize
bool candlerange1 = na
candlerange1 := barvalue < barsize and InSession(sessionTime)
//VOLUME
avg_vol_len = input(title=' Voulme EMA Length', defval=20)
factor = input(0.25, title='Volume Factor %')
pesado = volume > ta.sma(volume, avg_vol_len) * factor
draw=ta.barssince(candlerange1)<ta.barssince(candlerange1[1] or candlerange1[2]) and candlerange1 and pesado
barcolor = if InSession(sessionTime) and draw and pesado
color.black
else
na
barcolor(color=barcolor)
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var float barhigh2 = na
var float barlow2 = na
if InSession(sessionTime) and candlerange1 and (draw) and pesado // or (pesado and down))// or showLong)
barhigh2 := highbar1
barlow2 := lowbar1
barhigh3 = plot(barhigh2)//, plot=plot.style_circles)
barlow3 = plot(barlow2)//, plot=plot.style_circles
fill(barhigh3, barlow3, color = color.new(color.blue,50) )
//------------------------------------------------------------------------------------------------------------------------//
//EXTEND LINE
extendonoff1 = input(true, title ="Extend Line")
extend = input(5, title = "Extend Value")
f_y_given_x(_x1, _y1, _x2, _y2, _new_x) =>
_m = (_y2 - _y1) / (_x2 - _x1)
_b = _y1 - _m * _x1
_new_y = _m * _new_x + _b
_new_y
var ma_line1 = line.new(x1 = na, y1 = na, x2 = na, y2 = na, color = color.blue, extend = extend.none, style=line.style_solid)
var ma_line2 = line.new(x1 = na, y1 = na, x2 = na, y2 = na, color = color.blue, extend = extend.none, style=line.style_solid)
x1 = bar_index - 1
y1 = barhigh2[1]
x2 = bar_index
y2 = barhigh2
x3 = bar_index + extend
y3 = f_y_given_x(x1, y1, x2, y2, x3)
line.set_xy1(extendonoff1 ? ma_line1 : na, x = x1, y = y1)
line.set_xy2(extendonoff1 ? ma_line1 : na, x = x3, y = y3)
y22 = barlow2[1]
y33 = barlow2
y44 = f_y_given_x(x1, y22, x2, y33, x3)
line.set_xy1(extendonoff1 ? ma_line2 : na, x = x1, y = y22)
line.set_xy2(extendonoff1 ? ma_line2 : na, x = x3, y = y44) |
Customizable Moving Average Ribbon | https://www.tradingview.com/script/wywBpEfN-Customizable-Moving-Average-Ribbon/ | LeafAlgo | https://www.tradingview.com/u/LeafAlgo/ | 70 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © LeafAlgo
//@version=5
indicator('Customizable Moving Average Ribbon', shorttitle=' Custom MA ribbon', overlay=true)
//Inputs//
src= input.string('Renko Close', title='Source', options=['Classic Close', 'Classic Open', 'OHLC4', 'Renko Open', 'Renko Close'])
type = input.string('EMA', title='Moving Average Type Selection', options=['EMA', 'DEMA', 'TEMA','SMA', 'RMA', 'VWMA', 'WMA', 'SMMA', 'HULL'])
Color= input.string('Green/Red', title='Color Selection', options=['Green/Red','Purple/White','White/Blue','Silver/Orange','Teal/Orange'])
mode =input.string(title = 'Input Method', defval ='ATR', options=['Traditional', 'ATR'])
modevalue = input.int(title ='ATR Brick Size', defval = 14, minval = 1)
boxsize = input.float(title ='Traditional Brick Size', defval = 1, step= 0.001, minval = 0.0000001)
//Calculations//
conv_atr(value)=>
a = 0
num = syminfo.mintick
s = value
if na(s)
s := syminfo.mintick
if num < 1
for i = 1 to 20
num := num * 10
if num > 1
break
a := a +1
for x = 1 to a
s := s * 10
s := math.round(s)
for x = 1 to a
s := s / 10
s := s < syminfo.mintick ? syminfo.mintick : s
s
atrboxsize = conv_atr(ta.atr(modevalue))
float box = na
box := na(box[1]) ? mode == 'ATR' ? atrboxsize : boxsize : box[1]
reversal = 2
top = 0.0, bottom = 0.0
trend = 0
trend := barstate.isfirst ? 0 : nz(trend[1])
currentprice = 0.0
currentprice := close
float beginprice = na
beginprice := barstate.isfirst ? math.floor(open / box) * box : nz(beginprice[1])
openprice = 0.0
closeprice = 0.0
if trend == 0 and box * reversal <= math.abs(beginprice - currentprice)
if beginprice > currentprice
numcell = math.floor(math.abs(beginprice - currentprice) / box)
openprice := beginprice
closeprice := beginprice - numcell * box
trend := -1
if beginprice < currentprice
numcell = math.floor(math.abs(beginprice - currentprice) / box)
openprice := beginprice
closeprice := beginprice + numcell * box
trend := 1
if trend == -1
nok = true
if beginprice > currentprice and box <= math.abs(beginprice - currentprice)
numcell = math.floor(math.abs(beginprice - currentprice) / box)
closeprice := beginprice - numcell * box
trend := -1
beginprice := closeprice
nok := false
else
openprice := openprice == 0 ? nz(openprice[1]) : openprice
closeprice := closeprice == 0 ? nz(closeprice[1]) : closeprice
tempcurrentprice = close
if beginprice < tempcurrentprice and box * reversal <= math.abs(beginprice - tempcurrentprice) and nok //new column
numcell = math.floor(math.abs(beginprice - tempcurrentprice) / box)
openprice := beginprice + box
closeprice := beginprice + numcell * box
trend := 1
beginprice := closeprice
else
openprice := openprice == 0 ? nz(openprice[1]) : openprice
closeprice := closeprice == 0 ? nz(closeprice[1]) : closeprice
else
if trend == 1
nok = true
if beginprice < currentprice and box <= math.abs(beginprice - currentprice)
numcell = math.floor(math.abs(beginprice - currentprice) / box)
closeprice := beginprice + numcell * box
trend := 1
beginprice := closeprice
nok := false
else
openprice := openprice == 0 ? nz(openprice[1]) : openprice
closeprice := closeprice == 0 ? nz(closeprice[1]) : closeprice
tempcurrentprice = close
if beginprice > tempcurrentprice and box * reversal <= math.abs(beginprice - tempcurrentprice) and nok //new column
numcell = math.floor(math.abs(beginprice - tempcurrentprice) / box)
openprice := beginprice - box
closeprice := beginprice - numcell * box
trend := -1
beginprice := closeprice
else
openprice := openprice == 0 ? nz(openprice[1]) : openprice
closeprice := closeprice == 0 ? nz(closeprice[1]) : closeprice
box := ta.change(closeprice) ? mode == 'ATR' ? atrboxsize : boxsize : box
oprice =
trend == 1 ? nz(trend[1]) == 1 ? nz(closeprice[1]) - nz(box[1]) : nz(closeprice[1]) + nz(box[1]) :
trend == -1 ? nz(trend[1]) == -1 ? nz(closeprice[1]) + nz(box[1]) : nz(closeprice[1]) - nz(box[1]) :
nz(closeprice[1])
oprice := oprice < 0 ? 0 : oprice
//Color Options//
colorbull =
Color == 'Green/Red' ? color.green :
Color == 'Purple/White' ? color.white :
Color == 'White/Blue' ? color.white :
Color == 'Silver/Orange' ? color.silver :
Color == 'Teal/Orange' ? color.teal :
na
colorbear =
Color == 'Green/Red' ? color.red :
Color == 'Purple/White' ? color.purple :
Color == 'White/Blue' ? color.blue :
Color == 'Silver/Orange' ? color.orange :
Color == 'Teal/Orange' ? color.orange :
na
Source() =>
switch src
"Classic Close" => close
"Classic Open" => open
"OHLC4" => ohlc4
"Renko Open" => openprice
"Renko Close" => closeprice
//Moving Average Selection//
Multi_ma(type, src, len) =>
float result = 0
if type == 'EMA'
result := ta.ema(Source(), len)
if type == 'DEMA'
ema1 = ta.ema(Source(), len)
ema2 = ta.ema(ema1, len)
result := 2 * ema1 - ema2
if type == 'TEMA'
ema1 = ta.ema(Source(), len)
ema2 = ta.ema(ema1, len)
ema3 = ta.ema(ema2, len)
result := 3 * (ema1 - ema2) + ema3
if type == 'SMA'
result := ta.sma(Source(), len)
if type == 'RMA'
result := ta.rma(Source(), len)
if type == 'VWMA'
result := ta.vwma(Source(), len)
if type == 'WMA'
result := ta.wma(Source(), len)
if type == 'SMMA'
wma= ta.wma(Source(),len)
sma= ta.sma(Source(),len)
result := na(wma[1]) ? sma : (wma[1 ] * (len -1) + Source()) / len
if type == 'HULL'
result := ta.hma(Source(),len)
result
//MA Lengths//
MALen1=input.int(5, title='MA 1 Length')
MALen2=input.int(7, title='MA 2 Length')
MALen3=input.int(10, title='MA 3 Length')
MALen4=input.int(14, title='MA 4 Length')
MALen5=input.int(21, title='MA 5 Length')
MALen6=input.int(26, title='MA 6 Length')
MALen7=input.int(50, title='MA 7 Length')
MALen8=input.int(75, title='MA 8 Length')
MALen9=input.int(100, title='MA 9 Length')
MALen10=input.int(150, title='MA 10 Length')
MALen200=input.int(200, title='MA 200 Length')
//MA's//
MA1= Multi_ma(type, src, MALen1)
MA2= Multi_ma(type, src, MALen2)
MA3= Multi_ma(type, src, MALen3)
MA4= Multi_ma(type, src, MALen4)
MA5= Multi_ma(type, src, MALen5)
MA6= Multi_ma(type, src, MALen6)
MA7= Multi_ma(type, src, MALen7)
MA8= Multi_ma(type, src, MALen8)
MA9= Multi_ma(type, src, MALen9)
MA10= Multi_ma(type, src, MALen10)
MA200= Multi_ma(type, src, MALen200)
//MA Plots and Color Change//
maColor(MA, RefMA) =>
changeMA = ta.change(MA)
macolor = changeMA >= 0 and MA > RefMA ? colorbull : changeMA < 0 and MA > RefMA ? colorbear : changeMA <= 0 and MA < RefMA ? colorbear : changeMA >= 0 and MA < RefMA ? colorbull : color.gray
plot(MA1, color=maColor(MA1,MA200), linewidth =1, title='MA 1')
plot(MA2, color=maColor(MA2,MA200), linewidth =1, title='MA 2')
plot(MA3, color=maColor(MA3,MA200), linewidth =1, title='MA 3')
plot(MA4, color=maColor(MA4,MA200), linewidth =1, title='MA 4')
plot(MA5, color=maColor(MA5,MA200), linewidth =1, title='MA 5')
plot(MA6, color=maColor(MA6,MA200), linewidth =1, title='MA 6')
plot(MA7, color=maColor(MA7,MA200), linewidth =1, title='MA 7')
plot(MA8, color=maColor(MA8,MA200), linewidth =1, title='MA 8')
plot(MA9, color=maColor(MA9,MA200), linewidth =1, title='MA 9')
plot(MA10, color=maColor(MA10,MA200), linewidth =1, title='MA 10')
plot(MA200, color= MA200 <= closeprice ? colorbull : colorbear, linewidth=2, title='MA 200')
|
Energy_Arrows[Salty] | https://www.tradingview.com/script/Ra1vfbWj-Energy-Arrows-Salty/ | markmiotke | https://www.tradingview.com/u/markmiotke/ | 129 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © markmiotke
//@version=5
// Energy_Arrows[Salty]
// By Mark Miotke
// Initial Release: 2/20/2023
//This script quantifies the energy in a price move by comparing the relationship of 3 configurable exponential moving averages present on a slightly higher timeframe (chosen automatically based on the charts current period). It uses the closing price by default, but this is also configurable using the Source input. There are a few ways to use the information in this indicator. One is to use the values above zero (colored green) to provide a bullish bias for future price, and values below zero (colored red) indicating a bearish bias for future prices. This bias can be shown to be increasing or decreasing base on the upward or downward slope of the indicator. The green and red arrows can be enabled to show if the bias is strengthening or weakening based on the direction they are pointing. Finally, the height changes in the peaks of the indicator can be used to show divergence in the strength of extreme price moves to show when a pull back or reversal may occur.
indicator(title='Energy_Arrows[Salty]', shorttitle='Energy',overlay=false)
ShowZeroCrossArrows = input(true, title='Show Zero Cross Arrows', group = "Arrows")
ShowCrossArrows = input(true, title='Show Cross Arrows', group = "Arrows")
//New Inputs
//priceType default close
i_src = input.source(close, "Source", group = "Energy Oscillator")
// slowEmaLength default=26
i_lenSlow = input.int(26, "Slow EMA Length", step=1, group = "Energy Oscillator")
// fastEmaLength default=12
i_lenFast = input.int(12, "Fast EMA Length", step=1, group = "Energy Oscillator")
// smoothLength default=9
i_lenSmooth = input.int(9, "Smoothing Length", step=1, group = "Energy Oscillator")
// zoomFactor default=3
i_ZoomFactor = input.int(3, "Zoom Factor", step=1, group = "Energy Oscillator")
//funcEnergy(i_src, i_lenSlow, i_lenFast, i_lenSmooth, i_ZoomFactor)
Red = color.new(#FF0000, 50)
DarkRed = color.new(#BA0000, 50)
Green = color.new(#00FF00, 50)
DarkGreen = color.new(#00BA00, 50)
cRed = #FF0000
cGreen = #00FF00
cDarkRed = #BA0000
cDarkGreen = #00BA00
funcEnergy(eSrc, eLenSlow, eLenFast, eLenSmooth, eZoomFactor) =>
energy = ta.ema(eSrc, eLenFast) - ta.ema(eSrc, eLenSlow)
energySmoothed = ta.ema(energy, eLenSmooth)
(energy - energySmoothed) * eZoomFactor
//Resolution, e.g. '60' - 60 minutes, 'D' - daily, 'W' - weekly, 'M' - monthly, '5D' - 5 days, '12M' - one year, '3M' - one quarter
currentPeriod = timeframe.period
s2 = currentPeriod == '1' or currentPeriod == '3' ? request.security(syminfo.tickerid, '5', funcEnergy(i_src, i_lenSlow, i_lenFast, i_lenSmooth, i_ZoomFactor)) : currentPeriod == '5' ? request.security(syminfo.tickerid, '15', funcEnergy(i_src, i_lenSlow, i_lenFast, i_lenSmooth, i_ZoomFactor)) : currentPeriod == '10' ? request.security(syminfo.tickerid, '15', funcEnergy(i_src, i_lenSlow, i_lenFast, i_lenSmooth, i_ZoomFactor)) : currentPeriod == '15' ? request.security(syminfo.tickerid, '30', funcEnergy(i_src, i_lenSlow, i_lenFast, i_lenSmooth, i_ZoomFactor)) : currentPeriod == '30' ? request.security(syminfo.tickerid, '60', funcEnergy(i_src, i_lenSlow, i_lenFast, i_lenSmooth, i_ZoomFactor)) : currentPeriod == '45' ? request.security(syminfo.tickerid, '120', funcEnergy(i_src, i_lenSlow, i_lenFast, i_lenSmooth, i_ZoomFactor)) : currentPeriod == '60' or currentPeriod == '120' or currentPeriod == '180' or currentPeriod == '240' ? request.security(syminfo.tickerid, 'D', funcEnergy(i_src, i_lenSlow, i_lenFast, i_lenSmooth, i_ZoomFactor)) : currentPeriod == 'D' ? request.security(syminfo.tickerid, 'W', funcEnergy(i_src, i_lenSlow, i_lenFast, i_lenSmooth, i_ZoomFactor)) : currentPeriod == 'W' ? request.security(syminfo.tickerid, 'M', funcEnergy(i_src, i_lenSlow, i_lenFast, i_lenSmooth, i_ZoomFactor)) : currentPeriod == 'M' ? request.security(syminfo.tickerid, '3M', funcEnergy(i_src, i_lenSlow, i_lenFast, i_lenSmooth, i_ZoomFactor)) : na
c_color = s2 < 0 ? s2 <= s2[1] ? DarkRed : Red : s2 >= 0 ? s2 >= s2[1] ? Green : DarkGreen : na
//fill_Color = s2 < 0 ? s2 < s2[1] ? DarkRed : Red : s2 >= 0 ? s2 > s2[1] ? Green : DarkGreen : na
p1 = plot(s2, style=plot.style_area, color=c_color, linewidth=3)
zeroline = hline(0, title='Zero Line', color=color.black, linestyle=hline.style_dotted, linewidth=2)
plotshape(ShowZeroCrossArrows and ta.crossover(s2, 0) ? s2 : na, color=color.new(cDarkGreen, 0), style=shape.arrowup, location=location.absolute, size=size.huge)
plotshape(ShowCrossArrows and ta.crossover(s2, s2[1]) and s2 > 0 ? s2 : na, color=color.new(cDarkGreen, 0), style=shape.arrowup, location=location.absolute, size=size.huge)
plotshape(ShowCrossArrows and ta.crossunder(s2, s2[1]) and s2 > 0 ? s2 : na, color=color.new(cRed, 0), style=shape.arrowdown, location=location.absolute, size=size.normal)
plotshape(ShowZeroCrossArrows and ta.crossunder(s2, 0) ? s2 : na, color=color.new(cDarkRed, 0), style=shape.arrowdown, location=location.absolute, size=size.huge)
plotshape(ShowCrossArrows and ta.crossunder(s2, s2[1]) and s2 < 0 ? s2 : na, color=color.new(cDarkRed, 0), style=shape.arrowdown, location=location.absolute, size=size.huge)
plotshape(ShowCrossArrows and ta.crossover(s2, s2[1]) and s2 < 0 ? s2 : na, color=color.new(cGreen, 0), style=shape.arrowup, location=location.absolute, size=size.normal)
//fill(p1, plot(0, color=color.new(color.black, 0), linewidth=1), color=fill_Color)
|
5 Moving Averages | https://www.tradingview.com/script/6VG8fKC6-5-Moving-Averages/ | cyiwin | https://www.tradingview.com/u/cyiwin/ | 49 | 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/
// © cyiwin
//@version=5
indicator("5 Moving Averages", "5 MA", overlay = true, timeframe = "", timeframe_gaps = true)
use_ma1 = input.bool(defval = true, title = "", group = "MA 1", inline = "MA 1")
ma1_type = input.string(defval = "SMA", title = "Type", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group = "MA 1", inline = "MA 1")
ma1_length = input.int(defval = 25, title = "Length", group = "MA 1")
ma1_source = input(defval = close, title="Source", group = "MA 1")
ma1_x_offset = input.int(defval=0, minval=-500, maxval=500, title = "X offset", group = "MA 1")
ma1_y_multiplier = input.float(defval = 1, title = "Y multiplier", minval = .1, step = 0.1, group = "MA 1")
use_ma2 = input.bool(defval = true, title = "", group = "MA 2", inline = "MA 2")
ma2_type = input.string(defval = "SMA", title = "Type", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group = "MA 2", inline = "MA 2")
ma2_length = input.int(defval = 50, title = "Length", group = "MA 2")
ma2_source = input(defval = close, title="Source", group = "MA 2")
ma2_x_offset = input.int(defval=0, minval=-500, maxval=500, title = "X offset", group = "MA 2")
ma2_y_multiplier = input.float(defval = 1, title = "Y multiplier", minval = .1, step = 0.1, group = "MA 2")
use_ma3 = input.bool(defval = true, title = "", group = "MA 3", inline = "MA 3")
ma3_type = input.string(defval = "SMA", title = "Type", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group = "MA 3", inline = "MA 3")
ma3_length = input.int(defval = 100, title = "Length", group = "MA 3")
ma3_source = input(defval = close, title="Source", group = "MA 3")
ma3_x_offset = input.int(defval=0, minval=-500, maxval=500, title = "X offset", group = "MA 3")
ma3_y_multiplier = input.float(defval = 1, title = "Y multiplier", minval = .1, step = 0.1, group = "MA 3")
use_ma4 = input.bool(defval = true, title = "", group = "MA 4", inline = "MA 4")
ma4_type = input.string(defval = "SMA", title = "Type", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group = "MA 4", inline = "MA 4")
ma4_length = input.int(defval = 200, title = "Length", group = "MA 4")
ma4_source = input(defval = close, title="Source", group = "MA 4")
ma4_x_offset = input.int(defval=0, minval=-500, maxval=500, title = "X offset", group = "MA 4")
ma4_y_multiplier = input.float(defval = 1, title = "Y multiplier", minval = .1, step = 0.1, group = "MA 4")
use_ma5 = input.bool(defval = true, title = "", group = "MA 5", inline = "MA 5")
ma5_type = input.string(defval = "SMA", title = "Type", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group = "MA 5", inline = "MA 5")
ma5_length = input.int(defval = 300, title = "Length", group = "MA 5")
ma5_source = input(defval = close, title="Source", group = "MA 5")
ma5_x_offset = input.int(defval=0, minval=-500, maxval=500, title = "X offset", group = "MA 5")
ma5_y_multiplier = input.float(defval = 1, title = "Y multiplier", minval = .1, step = 0.1, group = "MA 5")
fun_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)
ma1 = fun_ma(ma1_source, ma1_length, ma1_type)
ma1 := ma1 * ma1_y_multiplier
ma2 = fun_ma(ma2_source, ma2_length, ma2_type)
ma2 := ma2 * ma2_y_multiplier
ma3 = fun_ma(ma3_source, ma3_length, ma3_type)
ma3 := ma3 * ma3_y_multiplier
ma4 = fun_ma(ma4_source, ma4_length, ma4_type)
ma4 := ma4 * ma4_y_multiplier
ma5 = fun_ma(ma5_source, ma5_length, ma5_type)
ma5 := ma5 * ma5_y_multiplier
plot(use_ma1? ma1 : na, title = "MA 1", offset = ma1_x_offset, color = color.rgb(33, 243, 65))
plot(use_ma2? ma2 : na, title = "MA 2", offset = ma2_x_offset, color = color.rgb(33, 243, 226))
plot(use_ma3? ma3 : na, title = "MA 3", offset = ma3_x_offset, color = color.rgb(44, 33, 243))
plot(use_ma4? ma4 : na, title = "MA 4", offset = ma4_x_offset, color = color.rgb(187, 33, 243))
plot(use_ma5? ma5 : na, title = "MA 5", offset = ma5_x_offset, color = color.rgb(243, 33, 68))
|
How To Import And Offset CSV Data | https://www.tradingview.com/script/KmceMbsx-How-To-Import-And-Offset-CSV-Data/ | allanster | https://www.tradingview.com/u/allanster/ | 119 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © allanster
//@version=5
indicator("How To Import And Offset CSV Data")
bump = input(true, '', inline = '1') // Enable/Disable offset of origin bar.
date = input.time(timestamp("19 Feb 2022 00:00 +0000"), "Shift Origin To", tooltip = 'When enabled use this offset for origin bar of data range.', inline = '1')
indx = not bump ? 0 : ta.valuewhen(time == date, bar_index, 0) // Origin bar index.
var data = array.new_float() // Create data array.
if bar_index == indx // If current bar is origin of data range populate the array.
// Paste CSV 👇 Example Normalized Data From Yahoo Finance BTCUSD Daily Close From February 19th, 2022 Thru February 19th, 2023.
data := array.from(
40122.15625, 38431.37891, 37075.28125, 38286.02734, 37296.57031, 38332.60938, 39214.21875, 39105.14844, 37709.78516, 43193.23438, 44354.63672, 43924.11719, 42451.78906,
39137.60547, 39400.58594, 38419.98438, 38062.03906, 38737.26953, 41982.92578, 39437.46094, 38794.97266, 38904.01172, 37849.66406, 39666.75391, 39338.78516, 41143.92969,
40951.37891, 41801.15625, 42190.65234, 41247.82422, 41077.99609, 42358.80859, 42892.95703, 43960.93359, 44348.73047, 44500.82813, 46820.49219, 47128.00391, 47465.73047,
47062.66406, 45538.67578, 46281.64453, 45868.94922, 46453.56641, 46622.67578, 45555.99219, 43206.73828, 43503.84766, 42287.66406, 42782.13672, 42207.67188, 39521.90234,
40127.18359, 41166.73047, 39935.51563, 40553.46484, 40424.48438, 39716.95313, 40826.21484, 41502.75000, 41374.37891, 40527.36328, 39740.32031, 39486.73047, 39469.29297,
40458.30859, 38117.46094, 39241.12109, 39773.82813, 38609.82422, 37714.87500, 38469.09375, 38529.32813, 37750.45313, 39698.37109, 36575.14063, 36040.92188, 35501.95313,
34059.26563, 30296.95313, 31022.90625, 28936.35547, 29047.75195, 29283.10352, 30101.26563, 31305.11328, 29862.91797, 30425.85742, 28720.27148, 30314.33398, 29200.74023,
29432.22656, 30323.72266, 29098.91016, 29655.58594, 29562.36133, 29267.22461, 28627.57422, 28814.90039, 29445.95703, 31726.39063, 31792.31055, 29799.08008, 30467.48828,
29704.39063, 29832.91406, 29906.66211, 31370.67188, 31155.47852, 30214.35547, 30111.99805, 29083.80469, 28360.81055, 26762.64844, 22487.38867, 22206.79297, 22572.83984,
20381.65039, 20471.48242, 19017.64258, 20553.27148, 20599.53711, 20710.59766, 19987.02930, 21085.87695, 21231.65625, 21502.33789, 21027.29492, 20735.47852, 20280.63477,
20104.02344, 19784.72656, 19269.36719, 19242.25586, 19297.07617, 20231.26172, 20190.11523, 20548.24609, 21637.58789, 21731.11719, 21592.20703, 20860.44922, 19970.55664,
19323.91406, 20212.07422, 20569.91992, 20836.32813, 21190.31641, 20779.34375, 22485.68945, 23389.43359, 23231.73242, 23164.62891, 22714.97852, 22465.47852, 22609.16406,
21361.70117, 21239.75391, 22930.54883, 23843.88672, 23804.63281, 23656.20703, 23336.89648, 23314.19922, 22978.11719, 22846.50781, 22630.95703, 23289.31445, 22961.27930,
23175.89063, 23809.48633, 23164.31836, 23947.64258, 23957.52930, 24402.81836, 24424.06836, 24319.33398, 24136.97266, 23883.29102, 23335.99805, 23212.73828, 20877.55273,
21166.06055, 21534.12109, 21398.90820, 21528.08789, 21395.01953, 21600.90430, 20260.01953, 20041.73828, 19616.81445, 20297.99414, 19796.80859, 20049.76367, 20127.14063,
19969.77148, 19832.08789, 19986.71289, 19812.37109, 18837.66797, 19290.32422, 19329.83398, 21381.15234, 21680.53906, 21769.25586, 22370.44922, 20296.70703, 20241.08984,
19701.21094, 19772.58398, 20127.57617, 19419.50586, 19544.12891, 18890.78906, 18547.40039, 19413.55078, 19297.63867, 18937.01172, 18802.09766, 19222.67188, 19110.54688,
19426.72070, 19573.05078, 19431.78906, 19312.09570, 19044.10742, 19623.58008, 20336.84375, 20160.71680, 19955.44336, 19546.84961, 19416.56836, 19446.42578, 19141.48438,
19051.41797, 19157.44531, 19382.90430, 19185.65625, 19067.63477, 19268.09375, 19550.75781, 19334.41602, 19139.53516, 19053.74023, 19172.46875, 19208.18945, 19567.00781,
19345.57227, 20095.85742, 20770.44141, 20285.83594, 20595.35156, 20818.47656, 20635.60352, 20495.77344, 20485.27344, 20159.50391, 20209.98828, 21147.23047, 21282.69141,
20926.48633, 20602.81641, 18541.27148, 15880.78027, 17586.77148, 17034.29297, 16799.18555, 16353.36523, 16618.19922, 16884.61328, 16669.43945, 16687.51758, 16697.77734,
16711.54688, 16291.83203, 15787.28418, 16189.76953, 16610.70703, 16604.46484, 16521.84180, 16464.28125, 16444.62695, 16217.32227, 16444.98242, 17168.56641, 16967.13281,
17088.66016, 16908.23633, 17130.48633, 16974.82617, 17089.50391, 16848.12695, 17233.47461, 17133.15234, 17128.72461, 17104.19336, 17206.43750, 17781.31836, 17815.65039,
17364.86523, 16647.48438, 16795.09180, 16757.97656, 16439.67969, 16906.30469, 16817.53516, 16830.34180, 16796.95313, 16847.75586, 16841.98633, 16919.80469, 16717.17383,
16552.57227, 16642.34180, 16602.58594, 16547.49609, 16625.08008, 16688.47070, 16679.85742, 16863.23828, 16836.73633, 16951.96875, 16955.07813, 17091.14453, 17196.55469,
17446.29297, 17934.89648, 18869.58789, 19909.57422, 20976.29883, 20880.79883, 21169.63281, 21161.51953, 20688.78125, 21086.79297, 22676.55273, 22777.62500, 22720.41602,
22934.43164, 22636.46875, 23117.85938, 23032.77734, 23078.72852, 23031.08984, 23774.56641, 22840.13867, 23139.28320, 23723.76953, 23471.87109, 23449.32227, 23331.84766,
22955.66602, 22760.10938, 23264.29102, 22939.39844, 21819.03906, 21651.18359, 21870.87500, 21788.20313, 21808.10156, 22220.80469, 24307.84180, na, na, na, 24601.94922
)
array.reverse(data) // Reverse index the data so that pop may be used instead of shift.
plot(array.size(data) < 1 ? na : array.pop(data), 'csv', #ffff00) // Plot and shrink dataset for bars within data range. |
Gann Square of 9 | https://www.tradingview.com/script/cSzck7Kl-Gann-Square-of-9/ | ThiagoSchmitz | https://www.tradingview.com/u/ThiagoSchmitz/ | 365 | 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/
// © ThiagoSchmitz
//@version=5
indicator("Gann Square of 9 by Thiago schmitz", "Gann Square of 9", overlay=true, max_lines_count = 500, max_labels_count = 500)
type tableCells
int column
int row
// ╔────────────────────────────────. ■ .──────────────────────────────────────▼
// ║ ⇌ • Inputs • ⇋
// ║┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈□┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈
var int levels = input.int(3, "Levels", group="calculation")
var float starting = input.float(20000.0, "Starting Number", group="calculation")
var float increase = input.float(500.0, "Increasing Number", group="calculation")
var string tablePosition = input.string("Top Right", "Square Position", ["Top Right", "Middle Right", "Bottom Right", "Top Left", "Middle Left", "Bottom Left"], group="table")
var float width = input.float(3.0, "Cell Width %", group="table")
var float height = input.float(4.0, "Cell Height %", group="table")
var int frameWidth = input.int(2, "Frame Width", group="table")
var color backgroundColor = input.color(color.new(color.black, 70), "Background Color", inline="color", group="table")
var color frameColor = input.color(color.new(color.white, 40), "Frame Color", inline="color", group="table")
var string tableTextSize = input.string(size.small, "Font Size", inline="fontcolor", group="table", options=[size.auto, size.tiny, size.small, size.normal, size.large, size.huge])
var color tableTextColor = input.color(color.new(color.white, 20), "Text Color", inline="fontcolor", group="table")
var bool showClosestValue = input.bool(true, "Show the closest value with the actual price", group="table")
var bool showDiagonal = input.bool(true, "Diagonals", group="diagonals", inline="diagonals")
var bool showDiagonalLevels = input.bool(true, "Levels", group="diagonals", inline="diagonals")
var bool showDiagonalLabels = input.bool(true, "Labels", group="diagonals", inline="diagonals")
var int diagonalLevelsShift = input.int(100, "Diagonal Levels Shift", minval = 1, maxval = 500, group="diagonals")
var int diagonalLabelShift = input.int(30, "Diagonal Levels Label Shift", minval = 1, maxval = 200, group="diagonals")
var color diagonalColor = input.color(color.new(color.white, 80), "Diagonal color", inline="diagonal", group="diagonals")
var color linesColor = input.color(color.new(color.white, 40), "Diagonal Levels Color", inline="diagonal", group="diagonals")
// ║┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈
// ║ ⇌ • Inputs • ⇋
// ╚─────────────────────────────────...───────────────────────────────────────▲
// ╔────────────────────────────────. ■ .──────────────────────────────────────▼
// ║ ⇌ • Variables • ⇋
// ║┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈□┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈
var string position = switch tablePosition
"Top Right" => position.top_right
"Middle Right" => position.middle_right
"Bottom Right" => position.bottom_right
"Top Left" => position.top_left
"Middle Left" => position.middle_left
=> position.bottom_left
var int size = levels * 2 + 1
var table tab = table.new(position, size, size, backgroundColor, frameColor, frameWidth, frameColor, frameWidth)
var tableCells[] coordinates = array.new<tableCells>()
var float[] values = array.new_float()
var float[] diagonalValues = array.new_float()
var line[] lines = array.new_line()
var label[] labels = array.new_label()
var int count = 1
var int layer = 2
// ║┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈
// ║ ⇌ • Variables • ⇋
// ╚─────────────────────────────────...───────────────────────────────────────▲
// ╔────────────────────────────────. ■ .──────────────────────────────────────▼
// ║ ⇌ • Functions • ⇋
// ║┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈□┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈
createCell(int c, int r, float v, color bgcolor=na) =>
table.cell(tab, c, r, str.tostring(v), width, height, tableTextColor, text_size=tableTextSize, bgcolor=bgcolor)
isDiagonal(int c, int l) => c % l == 1
getDiagonalColor() => showDiagonal ? diagonalColor : na
createCellWithValueAndColor(int column, int row, float value, color col) =>
createCell(column, row, value, col)
pivot = tableCells.new(column, row)
array.push(coordinates, pivot)
array.push(values, value)
// ║┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈
// ║ ⇌ • Functions • ⇋
// ╚─────────────────────────────────...───────────────────────────────────────▲
// ╔────────────────────────────────. ■ .──────────────────────────────────────▼
// ║ ⇌ • Build Square • ⇋
// ║┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈□┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈
if barstate.isfirst
int currentColumn = levels
int currentRow = levels
int doubleLevels = levels * 2
float startingValue = starting
createCell(currentColumn, currentRow, starting, diagonalColor)
array.push(diagonalValues, startingValue)
for i = 1 to doubleLevels by 1
int sign = i % 2 == 1 ? -1 : 1
int limit = i == 1 ? i / 2 : i
for j = 0 to i * 2 - 1 by 1
startingValue := startingValue + increase
count := count + 1
layer := math.sqrt(count) == layer + 1 ? layer + 2 : layer
isDiagonal = isDiagonal(count, layer)
col = isDiagonal ? getDiagonalColor() : na
currentColumn := j < limit ? currentColumn + sign : currentColumn
currentRow := j >= limit ? currentRow + sign : currentRow
createCellWithValueAndColor(currentColumn, currentRow, startingValue, col)
if isDiagonal
array.push(diagonalValues, startingValue)
if i == doubleLevels
for j = 0 to i - 1 by 1
startingValue := startingValue + increase
count := count + 1
isDiagonal = isDiagonal(count, layer)
col = isDiagonal ? getDiagonalColor() : na
currentColumn := currentColumn - sign
createCellWithValueAndColor(currentColumn, currentRow, startingValue, col)
if isDiagonal
array.push(diagonalValues, startingValue)
// ║┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈
// ║ ⇌ • Build Square • ⇋
// ╚─────────────────────────────────...───────────────────────────────────────▲
// ╔────────────────────────────────. ■ .──────────────────────────────────────▼
// ║ ⇌ • Update • ⇋
// ║┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈□┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈
if barstate.islast
index = array.binary_search_leftmost(values, close)
if index > 0
coord = array.get(coordinates, index)
table.cell_set_text_color(tab, coord.column, coord.row, color.red)
// ║┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈
// ║ ⇌ • Update • ⇋
// ╚─────────────────────────────────...───────────────────────────────────────▲
// ╔────────────────────────────────. ■ .──────────────────────────────────────▼
// ║ ⇌ • Build and Update Lines/Labels • ⇋
// ║┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈□┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈
if showDiagonalLevels
if array.size(lines) == 0 and array.size(diagonalValues) > 0
for i = 0 to array.size(diagonalValues) - 1 by 1
float value = array.get(diagonalValues, i)
array.push(lines, line.new(bar_index, value, bar_index, value, color=linesColor, extend=extend.right, style=line.style_dotted))
array.push(labels, label.new(bar_index, value, str.tostring(value), yloc=yloc.price, textcolor=linesColor, style=label.style_label_left, color=na))
else
for i = 0 to array.size(lines) - 1 by 1
line lin = array.get(lines, i)
label lab = array.get(labels, i)
line.set_x1(lin, bar_index - diagonalLevelsShift)
line.set_x2(lin, bar_index)
label.set_x(lab, bar_index + diagonalLabelShift)
// ║┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈
// ║ ⇌ • Build and Update Lines/Labels • ⇋
// ╚─────────────────────────────────...───────────────────────────────────────▲ |
Sniper Entry | https://www.tradingview.com/script/DPLwSNpQ-Sniper-Entry/ | michelsaliba72 | https://www.tradingview.com/u/michelsaliba72/ | 132 | 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/
// © michelsaliba72
//@version=5
indicator("Sniper Entry", overlay = true)
// Constants
riskRewardRatio = 3
startingCapital = 100
lotSize = 0.01
// Functions
bullishPinBar(c, o) =>
c > o and (c - o) / o >= 0.05
bearishPinBar(c, o) =>
c < o and (o - c) / o >= 0.05
bullishEngulfing(c, o) =>
c > o and close[1] < open[1]
bearishEngulfing(c, o) =>
c < o and close[1] > open[1]
// Indicator calculations
stochastic = ta.stoch(close, high, low, 14)
// Buy signal
longCondition = ta.crossover(stochastic, 20)
buySignal = longCondition and (bullishPinBar(close, open) or bullishEngulfing(close, open))
// Buy stop loss
buyStopLoss = longCondition ? low : na
// Buy target
buyTarget = (high + low) / 2 + riskRewardRatio * (high - low)
// Sell signal
shortCondition = ta.crossunder(stochastic, 80)
sellSignal = shortCondition and (bearishPinBar(close, open) or bearishEngulfing(close, open))
// Sell stop loss
sellStopLoss = shortCondition ? high : na
// Sell target
sellTarget = (high + low) / 2 - riskRewardRatio * (high - low)
// Plot signals and levels
plotshape(buySignal, title='Buy', location=location.belowbar, color=color.new(color.green, 0), size=size.small)
plot(buyStopLoss, title='Buy Stop Loss', color=color.red)
plot(buyTarget, title='Buy Target', color=color.green)
plotshape(sellSignal, title='Sell', location=location.abovebar, color=color.new(color.red, 0), size=size.small)
plot(sellStopLoss, title='Sell Stop Loss', color=color.green)
plot(sellTarget, title='Sell Target', color=color.red)
|
Anchored SMA | https://www.tradingview.com/script/xTeWDmxu-Anchored-SMA/ | downwithfate | https://www.tradingview.com/u/downwithfate/ | 12 | 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/
// © downwithfate
//@version=5
//This indicator is to keep a constant anchor point to the SMA across different timeframes from 1 minute to 1 week
//For example, if you set this to the 5 day SMA, when you go in to the 30 minute timeframe, it will scale to 65 tick SMA
indicator("Anchored SMA", overlay = true)
int anchor = input.int(5, title = "Anchor Ticks", minval = 1)
string anchorTF = input.timeframe(defval = 'D', title = "Anchored Timeframe")
int aMin = timeframe.in_seconds(anchorTF)/60
int pMin = timeframe.in_seconds()/60
//1 hour = 60 mins, 1 day = 390 mins, 1 week = 1950 mins
if aMin == 1440
aMin := 390
else if aMin == 10080
aMin := 1950
//period minutes
if pMin == 1440
pMin := 390
else if pMin == 10080
pMin := 1950
//convert TFs to mins
//get the number of ticks for the timeframe and find the anchored SMA
int ticks = anchor * aMin/pMin
aSMA = ta.sma(close, ticks)
plot(aSMA, title="aSMA", color=color.blue) |
BTC Performance Table / BTC Seasonality Visualization | https://www.tradingview.com/script/DOjMp0eS/ | Nuggeler | https://www.tradingview.com/u/Nuggeler/ | 32 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Nuggeler
// v1 12-02-2023
//@version=5
// What it does:
// This script visualizes Bitcoins "seasonality", in form of a coloured table (based on the idea from "BigBangTheory")
// The table shows which months do statistically perform better/worse in comparison to other months.
// How to use the script:
// Choose ticker "BLX" ("BraveNewCoin Liquid Index for Bitcoin"). It shows a complete BTC chart history.
// Set the chart time frame to weekly or daily. Table position on the screen and its colors are configurable.
// Table explanation:
// Cells show gain (green) or loss (red) for each month, in comparison to the previous month.
// The year column shows total gain (green) or loss (red) for that particular year.
// Each value is presented as a rounded, single digit, percentage number.
// How it works:
// The script calculates the difference between each monthly and yearly open & close price, storing them inside arrays.
// Then it populates the table, using those numbers and doing the cell coloring (yellow cell, if "no change" happened).
// German Short-Description
// Prozentuale Übersicht in Tabellenform der monatlichen, sowie der jährlichen, Performance des Bitcoin (basierend auf der Idee von "BigBangTheory").
// Zwecks vollständiger Darstellung muss der Ticker "BLX" ("BraveNewCoin Liquid Index for Bitcoin") im weekly oder daily timeframe aktiv sein.
indicator('BTC performance table / seasonality', "BTC-PT", overlay=true)
// check time frame
var correct_TF = (timeframe.isweekly and timeframe.multiplier == 1) or (timeframe.isdaily and timeframe.multiplier == 1)
// show info label, when time frame check failed
if not correct_TF and barstate.islastconfirmedhistory
labelText = "\n Use ticker BLX and set your time frame lower than monthly" + "\n or else you will not see full history and no results for " + str.tostring(year(time)) + "\n\nChart time frame is: " + timeframe.period
label.new(x=bar_index, y=close, style=label.style_label_left, color=color.new(#ff4800, 0), textcolor=color.rgb(0, 0, 0), size=size.large, text=labelText)
// table position options
table_pos=input.string(position.bottom_right, "Table Position", [position.top_left, position.top_center, position.top_right, position.middle_left, position.middle_center, position.middle_right, position.bottom_left, position.bottom_center, position.bottom_right])
// get monthly and yearly open and close prices
mo = request.security(syminfo.tickerid, 'M', open, gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_on)
mc = request.security(syminfo.tickerid, 'M', close, gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_on)
yo = request.security(syminfo.tickerid, '12M', open, gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_on)
yc = request.security(syminfo.tickerid, '12M', close, gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_on)
// check for new month or year
new_month = month(time) != month(time[1])
new_year = year(time) != year(time[1])
// calculate difference between open and close prices
mbar_pc = math.round(((mc - mo) * 100) / mo, precision = 2)
ybar_pc = math.round(((yc - yo) * 100) / yo, precision = 2)
// variables
cur_month_pc = 0.0
cur_year_pc = 0.0
cur_month_pc := barstate.islastconfirmedhistory ? 0.0 : +mbar_pc
cur_year_pc := barstate.islastconfirmedhistory ? 0.0 : +ybar_pc
var month_time = array.new_int(0)
var month_bh = array.new_float(0)
var year_time = array.new_int(0)
var year_bh = array.new_float(0)
// helper
last_computed = false
// populate arrays
if not na(cur_month_pc[1]) and (new_month or barstate.islastconfirmedhistory)
if last_computed[1]
array.pop(month_time)
array.push(month_bh, cur_month_pc[1])
array.push(month_time, time[1])
if not na(cur_year_pc[1]) and (new_year or barstate.islastconfirmedhistory)
if last_computed[1]
array.pop(year_time)
array.push(year_bh, cur_year_pc[1])
array.push(year_time, time[1])
last_computed := barstate.islast ? true : nz(last_computed[1])
// function for cell coloring
getCellColor(pc) =>
if pc > 0
input.color(color.rgb(75, 175, 75), "Positive Performance")
else if pc < 0
input.color(color.rgb(255, 100, 100), "Negative Performance")
else
color.rgb(175, 175, 75)
// initialize table
var monthly_table = table(na)
// table layout
if barstate.islastconfirmedhistory
monthly_table := table.new(table_pos, columns=14,rows = array.size(year_time) + 1, bgcolor = input.color(color.rgb(221, 221, 221), "Background Color"), frame_color = input.color(color.rgb(0, 100, 0),"Frame color") , frame_width = 4, border_color = input.color( color.rgb(255, 255, 255), "Border Color"), border_width = 2)
table.cell(monthly_table, 0, 0, '', bgcolor=#bbbbbb)
table.cell(monthly_table, 1, 0, 'Jan', bgcolor=#bbbbbb)
table.cell(monthly_table, 2, 0, 'Feb', bgcolor=#bbbbbb)
table.cell(monthly_table, 3, 0, 'Mar', bgcolor=#bbbbbb)
table.cell(monthly_table, 4, 0, 'Apr', bgcolor=#bbbbbb)
table.cell(monthly_table, 5, 0, 'May', bgcolor=#bbbbbb)
table.cell(monthly_table, 6, 0, 'Jun', bgcolor=#bbbbbb)
table.cell(monthly_table, 7, 0, 'Jul', bgcolor=#bbbbbb)
table.cell(monthly_table, 8, 0, 'Aug', bgcolor=#bbbbbb)
table.cell(monthly_table, 9, 0, 'Sep', bgcolor=#bbbbbb)
table.cell(monthly_table, 10, 0, 'Oct', bgcolor=#bbbbbb)
table.cell(monthly_table, 11, 0, 'Nov', bgcolor=#bbbbbb)
table.cell(monthly_table, 12, 0, 'Dec', bgcolor=#bbbbbb)
table.cell(monthly_table, 13, 0, 'Year', bgcolor=#8f8f8f)
// read arrays and populate table
for yi = 0 to array.size(year_bh) - 1
table.cell(monthly_table, 0, yi + 1, str.tostring(year(array.get(year_time, yi))), bgcolor=#adadad)
y_color = getCellColor(array.get(year_bh, yi))
table.cell(monthly_table, 13, yi + 1, str.tostring(math.round(array.get(year_bh, yi), precision = 1)) + "%", bgcolor=y_color)
for mi = 0 to array.size(month_time) - 1
m_row = year(array.get(month_time, mi)) - year(array.get(year_time, 0)) + 1
m_col = month(array.get(month_time, mi))
m_color = getCellColor(array.get(month_bh, mi))
table.cell(monthly_table, m_col, m_row, str.tostring(math.round(array.get(month_bh, mi), precision = 1)) + "%", bgcolor=m_color) |
Dynamic Reactor [CHE] | https://www.tradingview.com/script/BgC5o5F9/ | chervolino | https://www.tradingview.com/u/chervolino/ | 256 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © chervolino
// Dynamic Reactor [CHE] indicator displays dynamic support and resistance levels.
// Green lines represent resistance, red lines represent support, and gray lines represent areas of consolidation.
// The length of the indicator can be adjusted with the lengthMA input.
//@version=5
indicator("Dynamic Reactor [CHE]", shorttitle="DR [CHE]", overlay=true)
//Inputs
lengthMA = input(50, 'Length DR', inline='Inp', group='Input')
color green = input(#00e677f6, inline='Col', group='Color')
color red = input(#ff5252, inline='Col', group='Color')
color gray =input(#787b86, inline='Col', group='Color')
// Function
dyn_rea(src, len) =>
var smma = 0.0
h = ta.sma(src, len)
smma := na(smma[1]) ? h : (smma[1] * (len - 1) + src) / len
smma
// Calculation
hi=dyn_rea(high, lengthMA)
lo=dyn_rea(low, lengthMA)
mi=(hi-lo)/2+lo
// Plots
a=plot(hi,"", hlc3>hi?green:hlc3<lo?red:gray)
b=plot(lo,"", hlc3>hi?green:hlc3<lo?red:gray)
c=plot(mi,"", hlc3>hi?green:hlc3<lo?red:gray)
fill(a,b,hlc3>hi?color.new(green,60):hlc3<lo?color.new(red,60):color.gray) |
Pivot Trendlines with Breaks [HG] | https://www.tradingview.com/script/0ecaiSnU-Pivot-Trendlines-with-Breaks-HG/ | HoanGhetti | https://www.tradingview.com/u/HoanGhetti/ | 2,165 | 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/
// © HoanGhetti
//@version=5
indicator("Pivot Trendlines with Breaks [HG]", overlay = true, max_lines_count = 500)
import HoanGhetti/SimpleTrendlines/4 as tl
input_len = input.int(defval = 20, title = 'Pivot Length', minval = 1)
input_pivotType = input.string(defval = 'Normal', title = 'Pivot Type', options = ['Normal', 'Fast'], tooltip = 'Normal: Uses Pine\'s built-in pivot system.\n\nFast: Uses a custom pivot system that tracks every reversal.')
input_repaint = input.bool(defval = true, title = 'Repainting', tooltip = 'If disabled, it will wait for bar confirmation to avoid printing false alerts.')
input_targets = input.bool(defval = false, title = 'Target Levels')
input_bearC = input.color(defval = color.red, title = 'Bear Breakout', group = 'Styling')
input_bullC = input.color(defval = color.green, title = 'Bull Breakout', group = 'Styling')
input_extend = input.string(defval = extend.none, title = 'Extend', options = [extend.none, extend.right, extend.left, extend.both], group = 'Styling')
input_style = input.string(defval = line.style_dotted, title = 'Trendline Style', options = [line.style_dotted, line.style_dashed, line.style_solid], group = 'Styling')
input_tstyle = input.string(defval = line.style_dashed, title = 'Target Style', options = [line.style_dotted, line.style_dashed, line.style_solid], group = 'Styling')
input_override = input.bool(defval = false, title = 'Override Source', group = 'Override', tooltip = 'Overriding the source will allow the script to create trendlines on any specified source.')
input_useSrc = input.bool(defval = true, title = 'Use Source for Cross Detection', group = 'Override', tooltip = 'Instead of checking if the close value crossed trendline, check for the specified source.')
input_source = input.source(defval = low, title = 'Source', group = 'Override')
pl = fixnan(ta.pivotlow(input_override ? input_source : low, input_pivotType == 'Normal' ? input_len : 1, input_len))
ph = fixnan(ta.pivothigh(input_override ? input_source : high, input_pivotType == 'Normal' ? input_len : 1, input_len))
pivot(float pType) =>
pivot = pType == pl ? pl : ph
xAxis = ta.valuewhen(ta.change(pivot), bar_index, 0) - ta.valuewhen(ta.change(pivot), bar_index, 1)
prevPivot = ta.valuewhen(ta.change(pivot), pivot, 1)
pivotCond = ta.change(pivot) and (pType == pl ? pivot > prevPivot : pivot < prevPivot)
pData = tl.new(x_axis = xAxis, offset = input_len, strictMode = true, strictType = pType == pl ? 0 : 1)
pData.drawLine(pivotCond, prevPivot, pivot, input_override ? input_source : na)
pData
breakout(tl.Trendline this, float pType) =>
var bool hasCrossed = false
if ta.change(this.lines.startline.get_y1())
hasCrossed := false
this.drawTrendline(not hasCrossed)
confirmation = not hasCrossed and (input_repaint ? not hasCrossed : barstate.isconfirmed)
if (pType == pl ? (input_override and input_useSrc ? input_source : close) < this.lines.trendline.get_y2() : (input_override and input_useSrc ? input_source : close) > this.lines.trendline.get_y2()) and confirmation
hasCrossed := true
this.lines.startline.set_xy2(this.lines.trendline.get_x2(), this.lines.trendline.get_y2())
this.lines.trendline.set_xy2(na, na)
this.lines.startline.copy()
hasCrossed
plData = pivot(pl)
phData = pivot(ph)
style(tl.Trendline this, color col) =>
this.lines.startline.set_color(col), this.lines.trendline.set_color(col)
this.lines.startline.set_width(2), this.lines.trendline.set_width(2)
this.lines.trendline.set_style(input_style), this.lines.trendline.set_extend(input_extend)
style(plData, input_bearC), style(phData, input_bullC)
cu = breakout(plData, pl)
co = breakout(phData, ph)
plotshape(ta.change(cu) and cu ? plData.lines.startline.get_y2() : na, title = 'Bearish Breakout', style = shape.labeldown, color = input_bearC, textcolor = color.white, location = location.absolute, text = 'Br')
plotshape(ta.change(co) and co ? phData.lines.startline.get_y2() : na, title = 'Bullish Breakout', style = shape.labelup, color = input_bullC, textcolor = color.white, location = location.absolute, text = 'Br')
alertcondition(ta.change(cu) and cu, 'Bearish Breakout')
alertcondition(ta.change(co) and co, 'Bullish Breakout')
// Target Levels [v4 Update]
phData_target = tl.new(phData.values.changeInX)
plData_target = tl.new(plData.values.changeInX)
phData_target.drawLine(ta.change(phData.values.y1) and input_targets, phData.values.y2, phData.values.y2)
plData_target.drawLine(ta.change(plData.values.y1) and input_targets, plData.values.y2, plData.values.y2)
target_style(tl.Trendline this, color col) =>
this.lines.startline.set_style(input_tstyle)
this.lines.trendline.set_style(input_tstyle)
this.lines.startline.set_color(col)
this.lines.trendline.set_color(col)
target_style(plData_target, input_bearC)
target_style(phData_target, input_bullC)
breakout(phData_target, ph)
breakout(plData_target, pl) |
Weekday Change & Volume Average Table | https://www.tradingview.com/script/4pZxtbXX-Weekday-Change-Volume-Average-Table/ | NoaTrader | https://www.tradingview.com/u/NoaTrader/ | 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/
// © noafarin
//@version=5
indicator("Weekday Change & Volume Average Table",overlay = true)
var is_replay = input.bool(false,"Is in Replay Mode?")
var avgTable = table.new(position = position.top_right, columns = 5, rows = 8, bgcolor = color.white, border_width = 1)
candle_time_percent = not is_replay ? (1-(time_close - timenow)/(time_close - time)) : 1
var sat = array.new_float()
var sat_vol = array.new_float()
var sun = array.new_float()
var sun_vol = array.new_float()
var mon = array.new_float()
var mon_vol = array.new_float()
var tue = array.new_float()
var tue_vol = array.new_float()
var wed = array.new_float()
var wed_vol = array.new_float()
var thu = array.new_float()
var thu_vol = array.new_float()
var fri = array.new_float()
var fri_vol = array.new_float()
dif = (high-low)*100/low
if dayofweek == dayofweek.saturday
array.push(sat,dif)
array.push(sat_vol,volume)
if dayofweek == dayofweek.sunday
array.push(sun,dif)
array.push(sun_vol,volume)
if dayofweek == dayofweek.monday
array.push(mon,dif)
array.push(mon_vol,volume)
if dayofweek == dayofweek.tuesday
array.push(tue,dif)
array.push(tue_vol,volume)
if dayofweek == dayofweek.wednesday
array.push(wed,dif)
array.push(wed_vol,volume)
if dayofweek == dayofweek.thursday
array.push(thu,dif)
array.push(thu_vol,volume)
if dayofweek == dayofweek.friday
array.push(fri,dif)
array.push(fri_vol,volume)
if bar_index == last_bar_index
sat_avg = array.avg(sat)
sat_hl_last = sat.size() == 0 ? 0 : array.last(sat)
sat_vol_last = sat_vol.size() == 0 ? 0 : array.last(sat_vol)
sat_vol_avg = array.avg(sat_vol)
sun_avg = array.avg(sun)
sun_hl_last = sun.size() == 0 ? 0 : array.last(sun)
sun_vol_last = sun_vol.size() == 0 ? 0 : array.last(sun_vol)
sun_vol_avg = array.avg(sun_vol)
mon_avg = array.avg(mon)
mon_hl_last = mon.size() == 0 ? 0 : array.last(mon)
mon_vol_last = mon_vol.size() == 0 ? 0 : array.last(mon_vol)
mon_vol_avg = array.avg(mon_vol)
tue_avg = array.avg(tue)
tue_hl_last = tue.size() == 0 ? 0 : array.last(tue)
tue_vol_last = tue_vol.size() == 0 ? 0 : array.last(tue_vol)
tue_vol_avg = array.avg(tue_vol)
wed_avg = array.avg(wed)
wed_hl_last = wed.size() == 0 ? 0 : array.last(wed)
wed_vol_last = wed_vol.size() == 0 ? 0 : array.last(wed_vol)
wed_vol_avg = array.avg(wed_vol)
thu_avg = array.avg(thu)
thu_hl_last = thu.size() == 0 ? 0 : array.last(thu)
thu_vol_last = thu_vol.size() == 0 ? 0 : array.last(thu_vol)
thu_vol_avg = array.avg(thu_vol)
fri_avg = array.avg(fri)
fri_hl_last = fri.size() == 0 ? 0 : array.last(fri)
fri_vol_last = fri_vol.size() == 0 ? 0 : array.last(fri_vol)
fri_vol_avg = array.avg(fri_vol)
table.cell(table_id = avgTable, column = 1, row = 0, text = "HL Avg %", bgcolor=color.black,text_color = color.white,tooltip = "Average of (High-Low)/Low")
table.cell(table_id = avgTable, column = 2, row = 0, text = "VOL Avg "+syminfo.basecurrency, bgcolor=color.black,text_color = color.white,tooltip = "Average of Volume")
table.cell(table_id = avgTable, column = 3, row = 0, text = "Last HL %", bgcolor=color.black,text_color = color.white)
table.cell(table_id = avgTable, column = 4, row = 0, text = "Last VOL "+syminfo.basecurrency, bgcolor=color.black,text_color = color.white)
table.cell(table_id = avgTable, column = 0 , row = 1, text = "Saturday", bgcolor=color.black,text_color = color.white)
table.cell(table_id = avgTable, column = 1 , row = 1, text = str.tostring(sat_avg,"#.##"), bgcolor=color.black,text_color = color.white)
table.cell(table_id = avgTable, column = 2 , row = 1, text = str.tostring(sat_vol_avg,format.volume), bgcolor=color.black,text_color = color.white)
table.cell(table_id = avgTable, column = 3 , row = 1, text = str.tostring(sat_hl_last,"#.##"), bgcolor= sat_hl_last > sat_avg ? color.green : color.red ,text_color = color.white)
table.cell(table_id = avgTable, column = 4 , row = 1, text = str.tostring(sat_vol_last,format.volume), bgcolor= sat_vol_last > sat_vol_avg ? color.green : color.red ,text_color = color.white)
table.cell(table_id = avgTable, column = 0 , row = 2, text = "Sunday", bgcolor=color.black,text_color = color.white)
table.cell(table_id = avgTable, column = 1 , row = 2, text = str.tostring(sun_avg,"#.##"), bgcolor=color.black,text_color = color.white)
table.cell(table_id = avgTable, column = 2 , row = 2, text = str.tostring(sun_vol_avg,format.volume), bgcolor=color.black,text_color = color.white)
table.cell(table_id = avgTable, column = 3 , row = 2, text = str.tostring(sun_hl_last,"#.##"), bgcolor= sun_hl_last > sun_avg ? color.green : color.red ,text_color = color.white)
table.cell(table_id = avgTable, column = 4 , row = 2, text = str.tostring(sun_vol_last,format.volume), bgcolor= sun_vol_last > sun_vol_avg ? color.green : color.red ,text_color = color.white)
table.cell(table_id = avgTable, column = 0 , row = 3, text = "Monday", bgcolor=color.black,text_color = color.white)
table.cell(table_id = avgTable, column = 1 , row = 3, text = str.tostring(mon_avg,"#.##"), bgcolor=color.black,text_color = color.white)
table.cell(table_id = avgTable, column = 2 , row = 3, text = str.tostring(mon_vol_avg,format.volume), bgcolor=color.black,text_color = color.white)
table.cell(table_id = avgTable, column = 3 , row = 3, text = str.tostring(mon_hl_last,"#.##"), bgcolor= mon_hl_last > mon_avg ? color.green : color.red ,text_color = color.white)
table.cell(table_id = avgTable, column = 4 , row = 3, text = str.tostring(mon_vol_last,format.volume), bgcolor= mon_vol_last > mon_vol_avg ? color.green : color.red ,text_color = color.white)
table.cell(table_id = avgTable, column = 0 , row = 4, text = "Tueday", bgcolor=color.black,text_color = color.white)
table.cell(table_id = avgTable, column = 1 , row = 4, text = str.tostring(tue_avg,"#.##"), bgcolor=color.black,text_color = color.white)
table.cell(table_id = avgTable, column = 2 , row = 4, text = str.tostring(tue_vol_avg,format.volume), bgcolor=color.black,text_color = color.white)
table.cell(table_id = avgTable, column = 3 , row = 4, text = str.tostring(tue_hl_last,"#.##"), bgcolor= tue_hl_last > tue_avg ? color.green : color.red ,text_color = color.white)
table.cell(table_id = avgTable, column = 4 , row = 4, text = str.tostring(tue_vol_last,format.volume), bgcolor= tue_vol_last > tue_vol_avg ? color.green : color.red ,text_color = color.white)
table.cell(table_id = avgTable, column = 0 , row = 5, text = "Wednesday", bgcolor=color.black,text_color = color.white)
table.cell(table_id = avgTable, column = 1 , row = 5, text = str.tostring(wed_avg,"#.##"), bgcolor=color.black,text_color = color.white)
table.cell(table_id = avgTable, column = 2 , row = 5, text = str.tostring(wed_vol_avg,format.volume), bgcolor=color.black,text_color = color.white)
table.cell(table_id = avgTable, column = 3 , row = 5, text = str.tostring(wed_hl_last,"#.##"), bgcolor= wed_hl_last > wed_avg ? color.green : color.red ,text_color = color.white)
table.cell(table_id = avgTable, column = 4 , row = 5, text = str.tostring(wed_vol_last,format.volume), bgcolor= wed_vol_last > wed_vol_avg ? color.green : color.red ,text_color = color.white)
table.cell(table_id = avgTable, column = 0 , row = 6, text = "Thursday", bgcolor=color.black,text_color = color.white)
table.cell(table_id = avgTable, column = 1 , row = 6, text = str.tostring(thu_avg,"#.##"), bgcolor=color.black,text_color = color.white)
table.cell(table_id = avgTable, column = 2 , row = 6, text = str.tostring(thu_vol_avg,format.volume), bgcolor=color.black,text_color = color.white)
table.cell(table_id = avgTable, column = 3 , row = 6, text = str.tostring(thu_hl_last,"#.##"), bgcolor= thu_hl_last > thu_avg ? color.green : color.red ,text_color = color.white)
table.cell(table_id = avgTable, column = 4 , row = 6, text = str.tostring(thu_vol_last,format.volume), bgcolor= thu_vol_last > thu_vol_avg ? color.green : color.red ,text_color = color.white)
table.cell(table_id = avgTable, column = 0 , row = 7, text = "Friday", bgcolor=color.black,text_color = color.white)
table.cell(table_id = avgTable, column = 1 , row = 7, text = str.tostring(fri_avg,"#.##"), bgcolor=color.black,text_color = color.white)
table.cell(table_id = avgTable, column = 2 , row = 7, text = str.tostring(fri_vol_avg,format.volume), bgcolor=color.black,text_color = color.white)
table.cell(table_id = avgTable, column = 3 , row = 7, text = str.tostring(fri_hl_last,"#.##"), bgcolor= fri_hl_last > fri_avg ? color.green : color.red ,text_color = color.white)
table.cell(table_id = avgTable, column = 4 , row = 7, text = str.tostring(fri_vol_last,format.volume), bgcolor= fri_vol_last > fri_vol_avg ? color.green : color.red ,text_color = color.white)
table.cell_set_bgcolor(table_id = avgTable, column = 0, row = (dayofweek+1)%7, bgcolor=color.yellow)
table.cell_set_text_color(table_id = avgTable, column = 0, row = (dayofweek+1)%7,text_color = color.black)
table.cell(table_id = avgTable, column = 0, row = 0,text = str.tostring(math.max(sat.size(),mon.size()))+" Candles" ,text_color = color.black,tooltip = "Max(Saturdays,Mondays) meaning the average is caculated based on how many candles for each weekday") |
Intrabar Analyzer [Kioseff Trading] | https://www.tradingview.com/script/YqkWbG4M-Intrabar-Analyzer-Kioseff-Trading/ | KioseffTrading | https://www.tradingview.com/u/KioseffTrading/ | 1,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/
// © KioseffTrading
//@version=5
indicator("Intrabar Analyzer [Kioseff Trading]", max_labels_count = 500, max_lines_count = 500, max_boxes_count = 500, max_bars_back = 1)
import PineCoders/Time/3 as pct, import kaigouthro/hsvColor/15 as kai, import kaigouthro/EchoMorphicAverage/1 as wema, import TradingView/TechnicalRating/1 as rating
lowTFstr = input.string (defval = "1", title = "Lower Timeframe Chart", inline = "24")
rolling = input.bool (defval = false, title = "Show Current LTF Data Only", inline = "24")
strin = input.string (defval = "Scatter Plot", title = "Price x Vol Graph Characters", options = ["Numbers", "Scatter Plot"], group = "Rotation Graph")
scol = input.color (defval = color.blue, title = "Start Color (Early Data Color)", group = "Rotation Graph")
ecol = input.color (defval = #7e57c2, title = "End Color (Late Data Color)",group = "Rotation Graph")
typ = input.string (defval = "Traditional", title = "Price Data", options = ["Traditional", "Heikin-Ashi", "Kagi", "Point Figure", "Renko", "Line Break"], group = "Price Chart")
kRev = input.float (defval = 0.01, title = "Reversal Number", minval = 0.00000001, group = "Kagi")
pBox = input.string (defval = "Traditional", title = "Box Assignment Method", options = ["ATR", "Traditional"], group = "Point Figure")
lb = input.float (defval = 1, title = "ATR Length / Box Size", minval = 0.00000001, group = "Point Figure")
pRev = input.int (defval = 3, title = "Reversal Amount", minval = 1, group = "Point Figure")
pfl = input.string (defval = "Tiny", title = "Label Size", options = ["Auto", "Tiny", "Small", "Normal", "Large", "Huge"], group = "Point Figure")
rStyle = input.string (defval = "Traditional", title = "Box Assignment Menthod", options = ["ATR", "Traditional"], group = "Renko")
rba = input.float (defval = 0.1, title = "ATR Length / Box Size", minval = 0.00000001, group = "Renko")
rwick = input.bool (defval = false, title = "Wicks", group = "Renko")
linbr = input.int (defval = 1, title = "Number of Lines", minval = 1, group = "Line Break")
ind1 = input.string(defval = "Positive Volume Index", title = "Indicator 1", group = "Indicator Chart", options = ["RSI", "%k", "ROC", "MFI", "MFC", "OBV", "CCI", "BBW", "CMO" , "COG", "KCW", "MOM", "Negative Volume Index", "Positive Volume Index", "Price Volume Trend", "RANGE", "WPR"], inline = "30")
ind1Len = input.int (defval = 14, title = "Length", inline = "30", group = "Indicator Chart")
ind1Col = input.color (defval = color.purple, title = "", inline = "30", group = "Indicator Chart")
ind2 = input.string(defval = "Negative Volume Index", title = "Indicator 2", inline = "31",group = "Indicator Chart", options = ["RSI", "%k", "ROC", "MFI", "MFC", "OBV", "CCI", "BBW", "CMO" , "COG", "KCW", "MOM", "Negative Volume Index", "Positive Volume Index", "Price Volume Trend", "RANGE", "WPR"])
ind2Len = input.int (defval = 14, title = "Length", inline = "31",group = "Indicator Chart")
ind2Col = input.color (defval = color.lime, title = "", inline = "31",group = "Indicator Chart")
ind3 = input.string(defval = "Price Volume Trend", title = "Indicator 3", inline = "32" , group = "Indicator Chart", options = ["RSI", "%k", "ROC", "MFI", "MFC", "OBV", "CCI", "BBW", "CMO" , "COG", "KCW", "MOM", "Negative Volume Index", "Positive Volume Index", "Price Volume Trend", "RANGE", "WPR"])
ind3Len = input.int (defval = 14, title = "Length", inline = "32", group = "Indicator Chart")
ind3Col = input.color (defval = color.red, title = "", inline = "32", group = "Indicator Chart")
hideInd = input.bool (defval = false, title = "Hide Indicator Names ?", group = "Indicator Chart", inline = "40")
hideInd2 = input.bool (defval = false, title = "Hide Indicators ?", group = "Indicator Chart", inline = "40")
priceInd = input.string(defval = "Lin Reg", title = "Price Indicator", inline = "33", group = "Price Indicator", options = ["Lin Reg", "SMA", "WEMA", "EMA" ,"ALMA","HMA" ,"RMA" ,"WMA" ,"VWMA","VWAP","SWMA", "SAR", "Supertrend"])
priceIndLen= input.int (defval = 20, title = "Price Indicator Length", inline = "33", group = "Price Indicator")
priceIndCol= input.color (defval = color.rgb(255, 217, 0), title = "", inline = "33", group = "Price Indicator")
req() =>
switch typ
"Traditional" => syminfo.tickerid
"Heikin-Ashi" => ticker.heikinashi (syminfo.tickerid)
"Kagi" => ticker.kagi (syminfo.tickerid, kRev)
"Line Break" => ticker.linebreak (syminfo.tickerid, linbr)
"Renko" => ticker.renko (syminfo.tickerid, rStyle, rba, rwick)
"Point Figure"=> ticker.pointfigure (syminfo.tickerid, "hl", pBox, lb, pRev)
var int [] timeArray = array.new_int(), array.push(timeArray, math.round(time))
indPull(simple string indString, simple int indLen) =>
ad = close==high and close==low or high==low ? 0 : ((2*close-low-high)/(high-low))*volume
switch indString
"OBV" => ta.obv
"Negative Volume Index" => ta.nvi
"Positive Volume Index" => ta.pvi
"Price Volume Trend" => ta.pvt
"WPR" => ta.wpr (indLen)
"RSI" => ta.rsi (close, indLen)
"ROC" => ta.roc (close, indLen)
"MFI" => ta.mfi (close, indLen)
"CCI" => ta.cci (close, indLen)
"CMO" => ta.cmo (close, indLen)
"COG" => ta.cog (close, indLen)
"MOM" => ta.mom (close, indLen)
"RANGE" => ta.range(close, indLen)
"BBW" => ta.bbw (close, indLen, 2)
"KCW" => ta.kcw (close, indLen, 2)
"%k" => ta.stoch(close, high, low, indLen)
"MFC" => math.sum(ad, indLen) / math.sum(volume, indLen)
indPullPrice(simple string indString, simple int indLen) =>
switch indString
"VWAP" => ta.vwap
"SWMA" => ta.swma (close)
"SAR" => ta.sar (0.02, 0.02, 0.2)
"SMA" => ta.sma (close, priceIndLen)
"EMA" => ta.ema (close, priceIndLen)
"HMA" => ta.hma (close, priceIndLen)
"RMA" => ta.rma (close, priceIndLen)
"WMA" => ta.wma (close, priceIndLen)
"VWMA" => ta.vwma (close, priceIndLen)
"WEMA" => wema.wema(close, 0.5, priceIndLen)
"ALMA" => ta.alma (close, priceIndLen, 0.85, 6)
[s, d] = ta.supertrend(3, 3), [r, r1, r2] = rating.calcRatingAll()
[lowTFc, lowTFv, lowTFo, lowTFh, lowTFl, lowTFind1, lowTFind2, lowTFind3, lowTFpriceInd, lowTFr, lowTFd] =
request.security_lower_tf(req(), lowTFstr,
[
close, volume, open, high, low,
indPull(ind1, ind1Len),
indPull(ind2, ind2Len),
indPull(ind3, ind3Len),
priceInd == "Supertrend" ? s : indPullPrice(priceInd, priceIndLen),
r, str.tostring(hour) + ":" + str.tostring(minute)
])
type sequential
array <float> lowTFcopyC
array <float> lowTFcopyO
array <float> lowTFcopyV
array <float> lowTFcopyH
array <float> lowTFcopyL
array <float> lowTFcopyI1
array <float> lowTFcopyI2
array <float> lowTFcopyI3
array <float> lowTFcopyPI
array <float> lowTFcopyR
array <string> lowTFcopyD
var sequence = sequential.new(
array.new_float (), array.new_float(),
array.new_float (), array.new_float(),
array.new_float (), array.new_float(),
array.new_float (), array.new_float(),
array.new_float (), array.new_float(),
array.new_string()
)
insert(arr, arr2, i) =>
array.unshift(arr, array.get(arr2, i))
popClear(bool booL) =>
if booL == false
array.pop(sequence.lowTFcopyC ), array.pop(sequence.lowTFcopyV )
array.pop(sequence.lowTFcopyH ), array.pop(sequence.lowTFcopyL )
array.pop(sequence.lowTFcopyI1), array.pop(sequence.lowTFcopyI2)
array.pop(sequence.lowTFcopyI3), array.pop(sequence.lowTFcopyPI)
array.pop(sequence.lowTFcopyR ), array.pop(sequence.lowTFcopyD )
if booL == true
array.clear(sequence.lowTFcopyC ), array.clear(sequence.lowTFcopyV )
array.clear(sequence.lowTFcopyH ), array.clear(sequence.lowTFcopyL )
array.clear(sequence.lowTFcopyI1), array.clear(sequence.lowTFcopyI2)
array.clear(sequence.lowTFcopyI3), array.clear(sequence.lowTFcopyPI)
array.clear(sequence.lowTFcopyR ), array.clear(sequence.lowTFcopyD )
if rolling == true
if timeframe.change(timeframe.period)
popClear(true)
if array.size(lowTFc) > 0 and last_bar_index - bar_index <= 10
for i = 0 to array.size(lowTFc) - 1
insert(sequence.lowTFcopyC, lowTFc, i ), insert(sequence.lowTFcopyO, lowTFo, i )
insert(sequence.lowTFcopyV , lowTFv, i ), insert(sequence.lowTFcopyH , lowTFh, i )
insert(sequence.lowTFcopyL , lowTFl, i ), insert(sequence.lowTFcopyI1, lowTFind1, i )
insert(sequence.lowTFcopyI2, lowTFind2, i ), insert(sequence.lowTFcopyI3, lowTFind3, i )
insert(sequence.lowTFcopyPI, lowTFpriceInd, i), insert(sequence.lowTFcopyR , lowTFr, i )
insert(sequence.lowTFcopyD , lowTFd, i )
if rolling == false
if array.size(sequence.lowTFcopyC) > math.max(timeframe.multiplier, 30)
for i = 0 to array.size(sequence.lowTFcopyC) - math.max(timeframe.multiplier, 30)
popClear(false)
funcDraw(bx, draw, drawli, temp, len, str, y, i) =>
x1 = math.min(bar_index + 30, bar_index + 10 + array.size(sequence.lowTFcopyC)), styl = label.style_label_left
matrix.set(draw, i, 0, label.new(x1, y, text = str.tostring(array.min(temp), "##.00"),
size = size.small,
color = #ffffff00,
textcolor = color.white,
style = styl,
textalign = text.align_left
))
matrix.set(draw, i, 1, label.copy(matrix.get(draw, i, 0)))
label.set_xy(matrix.get(draw, i, 1), x1, box.get_top(bx)), label.set_text(matrix.get(draw, i, 1), str.tostring(array.max(temp), "##.00"))
matrix.set(draw, i, 2, label.new(math.round(math.avg(box.get_right(bx), box.get_left(bx))), box.get_top(bx), text = str ,
size = size.small,
color = #ffffff00,
textcolor = hideInd == false ? color.white : #ffffff00,
style = label.style_label_center
))
matrix.set(drawli, 3, 0, line.new(x1, math.avg(y, box.get_top(bx)), box.get_left(bx), math.avg(y, box.get_top(bx)),
color = color.gray,
style = line.style_dashed
))
funcAppend(lowTF, temp, yx, bx, mat, str, row, col) =>
if array.size(sequence.lowTFcopyC) > 2
for i = 1 to math.min(19, array.size(lowTF) - 1)
array.push(temp, array.get(lowTF, i))
for i = 1 to array.size(temp) - 1
if box.get_right(bx) - i < box.get_left(bx)
break
calcY = yx + (box.get_top(bx) * .9999 - yx) * (array.get(temp, i) - array.min(temp)) / (array.max(temp) - array.min(temp))
calcY1 = yx + (box.get_top(bx) * .9999 - yx) * (array.get(temp, i - 1) - array.min(temp)) / (array.max(temp) - array.min(temp))
matrix.set(mat, row, i,
line.new(
box.get_right(bx) - i + 1, calcY1,
box.get_right(bx) - i , calcY ,
color = col
))
setLeftRight(box boxObject, line lineObject, label labelObject, simple string borl, int x, bool Bool) =>
subtract = Bool == false ? 15 : x
switch borl
"Box" => box.set_left (boxObject , array.get(timeArray, array.indexof(timeArray, box.get_left (boxObject )) - subtract )),
box.set_right(boxObject , array.get(timeArray, array.indexof(timeArray, box.get_right(boxObject )) - subtract ))
"Line" => line.set_x1 (lineObject , array.get(timeArray, array.indexof(timeArray, line.get_x1 (lineObject )) - subtract )),
line.set_x2 (lineObject , array.get(timeArray, array.indexof(timeArray, line.get_x2 (lineObject )) - subtract ))
"Label" => label.set_x (labelObject, array.get(timeArray, array.indexof(timeArray, label.get_x (labelObject)) - subtract ))
sz = switch pfl
"Auto" => size.auto
"Tiny" => size.tiny
"Small" => size.small
"Normal" => size.normal
"Large" => size.large
"Huge" => size.huge
type indDraw
matrix <line> indLi
matrix <label> indLa
matrix <box> indBo
matrix <line> dynamicLine
array <box> priceBox
matrix <color> ratingColor
matrix <int> Quadrant
array <label> numLa
array <line> numLi
if barstate.islastconfirmedhistory
if array.size(sequence.lowTFcopyC) > bar_index
runtime.error("Not Enough Chart Space! Load An Asset With More Data.")
if timeframe.isminutes and timeframe.multiplier < 5
runtime.error("Try a Higher Timeframe!")
if barstate.islast
if array.size(line.all) > 0
for i = 0 to array.size(line.all) - 1
line.delete(array.shift(line.all))
if array.size(label.all) > 0
for i = 0 to array.size(label.all) - 1
label.delete(array.shift(label.all))
if array.size(box.all) > 0
for i = 0 to array.size(box.all) - 1
box.delete(array.shift(box.all))
draw = indDraw.new(
matrix.new<line>(8, 20), matrix.new<label>(8, 20), matrix.new<box>(8, 6),
matrix.new<line>(8, 1), array.new_box(), matrix.new<color>(4, 3), matrix.new<int>(1, 8, 0),
array.new_label(), array.new_line()), matx = matrix.new<float>(3, 0)
for i = 0 to array.size(sequence.lowTFcopyC) - 1
matrix.add_col(matx)
matrix.set(matx, 0, matrix.columns(matx) - 1, array.get(sequence.lowTFcopyC, i))
matrix.set(matx, 1, matrix.columns(matx) - 1, array.get(sequence.lowTFcopyV, i))
subX = matrix.submatrix(matx, 1, 2, 0, matrix.columns(matx))
subY = matrix.submatrix(matx, 0, 1, 0, matrix.columns(matx))
tr = matrix.transpose(subX)
skip = -1
matrix.sort(tr, order = order.descending)
calcX = math.max(math.abs(matrix.median(subX) - matrix.max(subX)), matrix.median(subX) - matrix.min(subX)) / 200
int [] calculation = array.new_int(), float [] calculation2 = array.new_float(), array.reverse(timeArray)
for x = 0 to matrix.columns(matx) - 1
for i = 0 to matrix.columns(matx) - 1
if matrix.get(subX, 0, x) == matrix.get(tr, i, 0) and skip != x
array.push(calculation, math.round(array.get(timeArray, i + math.round(array.size(sequence.lowTFcopyC) * 2.5))))
skip := x
array.reverse(timeArray)
for x = 0 to 20
yTop = math.max(math.abs(matrix.median(subY) - matrix.max(subY)), matrix.median(subY) - matrix.min(subY))
calcY = yTop * 2 / 20
append = switch yTop == math.abs(matrix.median(subY) - matrix.max(subY))
true => matrix.max(subY) - ((yTop * 2 / 20) * x)
=> matrix.min(subY) + ((yTop * 2 / 20) * x)
array.push(calculation2, append)
pricexvolGraph = box.new(
array.get(timeArray, array.size(timeArray) - math.round(matrix.columns(matx) * 3.5) - 1),
array.max(calculation2) * 1.0001,
array.get(timeArray, array.size(timeArray) - math.round(matrix.columns(matx) * 2.433) - 1),
array.min(calculation2) * .9999,
border_color = #ffffff,
bgcolor =na,
xloc = xloc.bar_time
)
mid = array.get(timeArray, array.size(timeArray) - math.round(matrix.columns(matx) * math.avg(3.5, 2.433))),
matrix.set(draw.indBo, 0, 0, box.new(
box.get_left(pricexvolGraph),
box.get_top(pricexvolGraph),
mid,
matrix.median(subY),
border_color = na,
bgcolor =color.new(color.blue, 85),
xloc = xloc.bar_time,
text_color = color.blue,
text_size = size.small
))
matrix.set(draw.indBo, 0, 1, box.new(
box.get_left(pricexvolGraph),
matrix.median(subY),
mid,
box.get_bottom(pricexvolGraph),
border_color = na,
bgcolor =color.new(color.yellow, 85),
xloc = xloc.bar_time,
text_color = color.yellow,
text_size = size.small
))
matrix.set(draw.indBo, 0, 2, box.new(
mid,
box.get_top(pricexvolGraph),
box.get_right(pricexvolGraph),
matrix.median(subY),
border_color = na,
bgcolor =color.new(color.green, 85),
xloc = xloc.bar_time,
text_color = color.green,
text_size = size.small
))
matrix.set(draw.indBo, 0, 3, box.new(
mid,
matrix.median(subY),
box.get_right(pricexvolGraph),
box.get_bottom(pricexvolGraph),
border_color = na,
bgcolor =color.new(color.red, 85),
xloc = xloc.bar_time,
text_color = color.red,
text_size = size.small
))
for i = 0 to array.size(timeArray) - 1
if array.get(timeArray, i) == box.get_right(matrix.get(draw.indBo, 0, 1))
matrix.set(draw.Quadrant, 0, 0, i)
if array.get(timeArray, i) == box.get_left (matrix.get(draw.indBo, 0, 1))
matrix.set(draw.Quadrant, 0, 1, i)
if array.get(timeArray, i) == box.get_right(matrix.get(draw.indBo, 0, 3))
matrix.set(draw.Quadrant, 0, 2, i)
if array.get(timeArray, i) == box.get_left (matrix.get(draw.indBo, 0, 3))
matrix.set(draw.Quadrant, 0, 3, i)
condQ = matrix.get(draw.Quadrant, 0, 0) - matrix.get(draw.Quadrant, 0, 1) >
matrix.get(draw.Quadrant, 0, 2) - matrix.get(draw.Quadrant, 0, 3)
if condQ
box.set_right(matrix.get(draw.indBo, 0, 0), array.get(timeArray, matrix.get(draw.Quadrant, 0, 0) - 1))
box.set_right(matrix.get(draw.indBo, 0, 1), array.get(timeArray, matrix.get(draw.Quadrant, 0, 0) - 1))
box.set_left (matrix.get(draw.indBo, 0, 2), array.get(timeArray, matrix.get(draw.Quadrant, 0, 3) - 1))
box.set_left (matrix.get(draw.indBo, 0, 3), array.get(timeArray, matrix.get(draw.Quadrant, 0, 3) - 1))
matrix.set(draw.Quadrant, 0, 0, matrix.get(draw.Quadrant, 0, 0) - 1)
matrix.set(draw.Quadrant, 0, 3, matrix.get(draw.Quadrant, 0, 3) - 1) // condChange
condQ := matrix.get(draw.Quadrant, 0, 0) - matrix.get(draw.Quadrant, 0, 1) >
matrix.get(draw.Quadrant, 0, 2) - matrix.get(draw.Quadrant, 0, 3)
if condQ // is still true
box.set_right (matrix.get(draw.indBo, 0, 2), array.get(timeArray, matrix.get(draw.Quadrant, 0, 2) + 1))
box.set_right (matrix.get(draw.indBo, 0, 3), array.get(timeArray, matrix.get(draw.Quadrant, 0, 2) ))
box.set_right (pricexvolGraph, array.get(timeArray, matrix.get(draw.Quadrant, 0, 2) + 1))
box.set_right (matrix.get(draw.indBo, 0, 3), array.get(timeArray, matrix.get(draw.Quadrant, 0, 2) + 1))
matrix.set(draw.indLi, 6, 1,
line.new(box.get_left(pricexvolGraph) , matrix.median(subY) ,
box.get_right (pricexvolGraph) , array.median(sequence.lowTFcopyC),
color = color.gray , xloc = xloc.bar_time
))
for i = 0 to array.size(calculation) - 1
col = kai.hsv_gradient(i, 0, array.size(calculation) - 1, scol, ecol)
switch
array.get(sequence.lowTFcopyC, i) >= array.median(sequence.lowTFcopyC) and array.get(sequence.lowTFcopyV, i) >= array.median(sequence.lowTFcopyV) =>
matrix.set(draw.Quadrant, 0, 4, matrix.get(draw.Quadrant, 0, 4) + 1)
array.get(sequence.lowTFcopyC, i) >= array.median(sequence.lowTFcopyC) and array.get(sequence.lowTFcopyV, i) < array.median(sequence.lowTFcopyV) =>
matrix.set(draw.Quadrant, 0, 5, matrix.get(draw.Quadrant, 0, 5) + 1)
array.get(sequence.lowTFcopyC, i) < array.median(sequence.lowTFcopyC) and array.get(sequence.lowTFcopyV, i) >= array.median(sequence.lowTFcopyV) =>
matrix.set(draw.Quadrant, 0, 6, matrix.get(draw.Quadrant, 0, 6) + 1)
array.get(sequence.lowTFcopyC, i) < array.median(sequence.lowTFcopyC) and array.get(sequence.lowTFcopyV, i) < array.median(sequence.lowTFcopyV) =>
matrix.set(draw.Quadrant, 0, 7, matrix.get(draw.Quadrant, 0, 7) + 1)
array.push(draw.numLa, label.new(array.get(calculation, i), array.get(sequence.lowTFcopyC, i),
color = #ffffff00, textcolor = col,
text = strin == "Numbers" ? str.tostring(i) : "◉",
style = label.style_label_center,
xloc = xloc.bar_time,
size = size.tiny,
tooltip = array.get(sequence.lowTFcopyD, i) + "\n" +
str.tostring(array.get(sequence.lowTFcopyC, i), format.mintick)
+ "\n" + str.tostring(array.get(sequence.lowTFcopyV, i), format.volume)
))
for i = 0 to array.size(calculation2) - 1
array.push(draw.numLi, line.new( array.get(timeArray, array.size(timeArray) - math.round(matrix.columns(matx) * 3.51) - 2),
array.get(calculation2, i), box.get_left(pricexvolGraph), array.get(calculation2, i),
xloc = xloc.bar_time,
color = color.gray
))
array.push(draw.numLa, label.new(array.get(timeArray, array.size(timeArray) - math.round(matrix.columns(matx) * 3.51) - 2),
array.get(calculation2, i), str.tostring(array.get(calculation2, i), format.mintick),
color = #ffffff00,
style = label.style_label_right,
textcolor = color.white,
size = size.tiny,
xloc = xloc.bar_time
))
for i = 0 to 7
l = box.get_left(pricexvolGraph), t = box.get_top(pricexvolGraph), b = box.get_bottom(pricexvolGraph)
ri = box.get_right(pricexvolGraph), up = label.style_label_up, dn = label.style_label_down
lf = label.style_label_left, tiny = size.tiny, small = size.small, maxVol = array.max(sequence.lowTFcopyV)
form = format.volume, iTrack = -1
[x, y, text, styl, tcol, siz] = switch i != iTrack
true and i == 0 => [l, t, str.tostring(t, format.mintick), dn, color.white , tiny ]
true and i == 1 => [l, b, str.tostring(b, format.mintick), up, color.white , tiny ]
true and i == 2 => [ri, t, str.tostring(maxVol, form ), lf, color.white , tiny ]
true and i == 3 => [l, t * 1.0001, "High Price / Low Volume" , dn, color.blue , small ]
true and i == 4 => [ri, t * 1.0001, "High Price / High Volume" , dn, color.green , small ]
true and i == 5 => [ri, b * .9999, "Low Price / High Volume" , up, color.red , small ]
true and i == 6 => [l, b * .9999, "Low Price / Low Volume" , up, color.yellow, small ]
true and i == 7 => [
box.get_right(matrix.get(draw.indBo, 0, 1)), b,
str.tostring(array.median(sequence.lowTFcopyV), format.volume) + " (Median Volume)", up,
color.white, size.small
]
matrix.set(draw.indLa, 6, i, label.new(x, y, text, xloc = xloc.bar_time, color = #ffffff00,
size = siz,
textcolor = tcol,
style = styl
))
box.set_text(matrix.get(draw.indBo, 0, 0), str.tostring(matrix.get(draw.Quadrant, 0, 5)))
box.set_text(matrix.get(draw.indBo, 0, 2), str.tostring(matrix.get(draw.Quadrant, 0, 4)))
box.set_text(matrix.get(draw.indBo, 0, 3), str.tostring(matrix.get(draw.Quadrant, 0, 6)))
box.set_text(matrix.get(draw.indBo, 0, 1), str.tostring(matrix.get(draw.Quadrant, 0, 7)))
kLine = array.new_line(), kLineConnect = array.new_line()
if array.size(sequence.lowTFcopyC) > 0
// array.reverse(sequence.lowTFcopyC), array.reverse(sequence.lowTFcopyH)
// array.reverse(sequence.lowTFcopyL), array.reverse(sequence.lowTFcopyO)
colZ = switch array.get(sequence.lowTFcopyC, 0) >= array.get(sequence.lowTFcopyO, 0)
true => color.green
=> color.red
if typ != "Kagi"
array.push(draw.priceBox, box.new(
left = time[1],
top = math.max(array.get(sequence.lowTFcopyC, 0), array.get(sequence.lowTFcopyO, 0)),
right = pct.timeFrom("bar", 1, "chart") ,
bottom = math.min(array.get(sequence.lowTFcopyC, 0), array.get(sequence.lowTFcopyO, 0)),
bgcolor = color.new(colZ, 95),
border_color = colZ,
xloc = xloc.bar_time
))
for i = 0 to 1
iTrack = -1
[y1, y2] = switch i != iTrack
true and i == 0 => [array.get(sequence.lowTFcopyH, 0), box.get_top (array.get(draw.priceBox, 0))]
=> [array.get(sequence.lowTFcopyL, 0), box.get_bottom(array.get(draw.priceBox, 0))]
matrix.set(draw.dynamicLine, i , 0, line.new(
x1 = time,
y1 = y1,
x2 = time,
y2 = y2,
color = colZ,
xloc = xloc.bar_time
))
else
array.push(kLine, line.new(
x1 = time, y1 = array.get(sequence.lowTFcopyC, 0),
x2 = pct.timeFrom("bar", 1, "chart"),
y2 = array.get(sequence.lowTFcopyC, 0),
width = 2, xloc = xloc.bar_time
))
if array.size(sequence.lowTFcopyC) > 1
X1 = 4, X2 = 2, X3 = 3
if typ == "Kagi"
array.reverse(timeArray)
for i = 1 to array.size(sequence.lowTFcopyC) - 1
matrix.add_col(draw.dynamicLine, matrix.columns(draw.dynamicLine))
colA = switch array.get(sequence.lowTFcopyC, i) >= array.get(sequence.lowTFcopyO, i)
true => color.green
false => color.red
if typ != "Kagi"
array.push(draw.priceBox, box.new(array.get(timeArray, array.size(timeArray) - X1),
math.max(array.get(sequence.lowTFcopyC, i), array.get(sequence.lowTFcopyO, i)),
array.get(timeArray, array.size(timeArray) - X2),
math.min(array.get(sequence.lowTFcopyC, i), array.get(sequence.lowTFcopyO, i)),
bgcolor = color.new(colA, 95), border_color = colA,
xloc = xloc.bar_time
))
x1 = array.get(timeArray, array.size(timeArray) - X3)
matrix.set(draw.dynamicLine, 0, matrix.columns(draw.dynamicLine) - 1, line.new(x1,
array.get(sequence.lowTFcopyH, i), x1, box.get_top(array.get(draw.priceBox, i)),
color = colA, xloc = xloc.bar_time
))
matrix.set(draw.dynamicLine, 1, matrix.columns(draw.dynamicLine) - 1, line.new(x1,
array.get(sequence.lowTFcopyL, i), x1, box.get_bottom(array.get(draw.priceBox, i)),
color = colA, xloc = xloc.bar_time
))
X1 += 2, X2 += 2, X3 += 2
else
array.push(kLine, line.new(array.get(timeArray, i), array.get(sequence.lowTFcopyC, i),
array.get(timeArray, i - 1), array.get(sequence.lowTFcopyC, i),
width = 2, xloc = xloc.bar_time
))
array.push(kLineConnect, line.new(line.get_x1(array.get(kLine, i - 1)),
line.get_y1(array.get(kLine, i - 1)),
line.get_x1(array.get(kLine, i - 1)),
line.get_y1(array.get(kLine, i)),
width = 2, xloc = xloc.bar_time
))
if i == array.size(sequence.lowTFcopyC) - 1
array.reverse(timeArray)
min = math.round(20e20)
if array.size(draw.priceBox) > 0 and typ != "Kagi"
for i = 0 to array.size(draw.priceBox) - 1
min := math.min(box.get_left(array.get(draw.priceBox, i)), min)
if array.size(kLine) > 0 and typ == "Kagi"
for i = 0 to array.size(kLine) - 1
min := math.min(line.get_x1(array.get(kLine, i)), min)
min := array.get(timeArray, array.indexof(timeArray, min) - 1)
matrix.set(draw.indBo, 3, 0, box.new(min, array.max(sequence.lowTFcopyH) ,
pct.timeFrom("bar", 1, "chart"), array.min(sequence.lowTFcopyL) ,
bgcolor = color.new(color.blue, 95),
border_color = color.white, xloc = xloc.bar_time
))
left = box.get_left (matrix.get(draw.indBo, 3, 0)), top = box.get_top (matrix.get(draw.indBo, 3, 0))
right = box.get_right(matrix.get(draw.indBo, 3, 0)), bottom = box.get_bottom(matrix.get(draw.indBo, 3, 0))
if typ == "Kagi"
if array.size(kLine) > 2
array.reverse(kLine), array.reverse(kLineConnect)
bool ixb = na, bool ixf = na
if line.get_y1(array.get(kLine, 1)) >= line.get_y1(array.get(kLine, 0))
line.set_color(array.get(kLine, 1), color.lime), line.set_color(array.get(kLine, 0), color.lime)
line.set_color(array.get(kLineConnect, 0), color.lime), ixb := true
else
line.set_color(array.get(kLine, 1), color.red), line.set_color(array.get(kLine, 0), color.red)
line.set_color(array.get(kLineConnect, 0), color.red), ixb := false
for i = 2 to array.size(kLine) - 1
if ixb == true
ixf := true
else
ixf := false
ix = line.get_y1(array.get(kLine, i))
ix1 = line.get_y1(array.get(kLine, i - 1))
ix2 = line.get_y1(array.get(kLine, i - 2))
if ix >= ix1 and ix >= ix2
ixb := true
if ix < ix1 and ix < ix2
ixb := false
switch ixb
true => line.set_color(array.get(kLine, i), color.lime),
line.set_color(array.get(kLineConnect, i - 1), color.lime)
=> line.set_color(array.get(kLine, i), color.red),
line.set_color(array.get(kLineConnect, i - 1), color.red)
if ixb == true and ixf == false
line.new(line.get_x1(array.get(kLine, i)), ix1, line.get_x1(array.get(kLine, i)), ix2, width = 2, xloc = xloc.bar_time, color = color.red)
line.new(line.get_x1(array.get(kLine, i)), ix2, line.get_x1(array.get(kLine, i)), ix , width = 2, xloc = xloc.bar_time, color = color.lime)
line.delete(array.get(kLineConnect, i - 1))
if ixb == false and ixf == true
line.new(line.get_x1(array.get(kLine, i)), ix1, line.get_x1(array.get(kLine, i)), ix2, width = 2, xloc = xloc.bar_time, color = color.lime)
line.new(line.get_x1(array.get(kLine, i)), ix2, line.get_x1(array.get(kLine, i)), ix , width = 2, xloc = xloc.bar_time, color = color.red)
line.delete(array.get(kLineConnect, i - 1))
if array.size(sequence.lowTFcopyC) > 1
if priceInd == "Lin Reg"
finSlo = array.new_float()
x = array.new_float() , y = array.sum(sequence.lowTFcopyC)
xy = array.new_float(), x2 = array.new_float()
for i = 0 to array.size(sequence.lowTFcopyC) - 1
array.push(x, i + 1)
for i = 0 to array.size(sequence.lowTFcopyC) - 1
array.push(xy, (i + 1) * array.get(sequence.lowTFcopyC, i))
array.push(x2, math.pow(i + 1, 2))
mTop = ((array.size(x) * array.sum(xy)) - (array.sum(x) * y))
mBot = array.size(x) * array.sum(x2) - math.pow(array.sum(x), 2)
m = mTop / mBot, bx = (y - m * array.sum(x)) / array.size(x)
for i = 0 to array.size(sequence.lowTFcopyC) - 1
array.push(finSlo, (m * (i + 1)) + bx)
array.reverse(finSlo)
for i = 2 to 4
iTrack = -1, fin0 = array.get(finSlo, 0), finLast = array.get(finSlo, array.size(finSlo) - 1)
[y1, y2, styl, col] = switch i != iTrack
true and i == 2 => [fin0, finLast, line.style_dashed, fin0 >= finLast ? color.red : color.green]
true and i == 3 => [fin0 + (array.stdev(sequence.lowTFcopyC)), finLast + array.stdev(sequence.lowTFcopyC), line.style_solid, color.blue]
true and i == 4 => [fin0 - (array.stdev(sequence.lowTFcopyC)), finLast - array.stdev(sequence.lowTFcopyC), line.style_solid, color.blue]
matrix.set(draw.dynamicLine, i, 0, line.new(min, y1, time, y2,
color = col,
style = styl,
xloc = xloc.bar_time,
width = i == 2 ? 2 : 1
))
linefill.new(matrix.get(draw.dynamicLine, 3, 0), matrix.get(draw.dynamicLine, 4, 0),
array.get(finSlo, 0) >= array.get(finSlo, array.size(finSlo) - 1) ?
color.new(color.red, 95) : color.new(color.green, 95))
box.set_bottom(matrix.get(draw.indBo, 3, 0),
math.min(
array.min(sequence.lowTFcopyL), box.get_bottom(matrix.get(draw.indBo, 3, 0)),
line.get_y1(matrix.get(draw.dynamicLine, 4, 0)), line.get_y2(matrix.get(draw.dynamicLine, 4, 0))
))
box.set_top(matrix.get(draw.indBo, 3, 0),
math.max(
array.max(sequence.lowTFcopyH), box.get_top(matrix.get(draw.indBo, 3, 0)),
line.get_y1(matrix.get(draw.dynamicLine, 3, 0)), line.get_y2(matrix.get(draw.dynamicLine, 3, 0))
))
top := box.get_top (matrix.get(draw.indBo, 3, 0))
bottom := box.get_bottom(matrix.get(draw.indBo, 3, 0))
else
//array.reverse(sequence.lowTFcopyPI)
line [] priceIndLine = array.new_line()
array.reverse(timeArray) , float [] tineIndLine = array.new_float()
array.push(priceIndLine, line.new(time[1], array.get(sequence.lowTFcopyPI, 1),
time, array.get(sequence.lowTFcopyPI, 0),
width = 2,color = priceIndCol,
xloc = xloc.bar_time,
style = priceInd == "SAR" ?
line.style_dotted :
line.style_solid
))
if array.size(sequence.lowTFcopyPI) > 2
for i = 2 to array.size(sequence.lowTFcopyPI) - 1
array.push(priceIndLine, line.new(array.get(timeArray, i * 2),
array.get(sequence.lowTFcopyPI, i), line.get_x1(array.get(priceIndLine, array.size(priceIndLine) - 1)),
array.get(sequence.lowTFcopyPI, i - 1), width = 2, color= priceIndCol, xloc = xloc.bar_time,
style = priceInd == "SAR" ? line.style_dotted : line.style_solid
))
if array.get(timeArray, i * 2) <= left
break
if priceInd == "SAR" or priceInd == "Supertrend"
if array.size(priceIndLine) > 1
for i = 0 to array.size(priceIndLine) - 1
switch line.get_y2(array.get(priceIndLine, i)) >= array.get(sequence.lowTFcopyC, i)
true => line.set_color(array.get(priceIndLine, i), color.red)
=> line.set_color(array.get(priceIndLine, i), color.lime)
if i >= 1
if array.get(sequence.lowTFcopyC, i) >= line.get_y2(array.get(priceIndLine, i)) and array.get(sequence.lowTFcopyC, i) <= line.get_y2(array.get(priceIndLine, i - 1))
or array.get(sequence.lowTFcopyC, i) <= line.get_y2(array.get(priceIndLine, i)) and array.get(sequence.lowTFcopyC, i) >= line.get_y2(array.get(priceIndLine, i - 1))
line.delete(array.get(priceIndLine, i - 1))
array.reverse(timeArray)
box.set_bottom(matrix.get(draw.indBo, 3, 0), math.min(array.min(sequence.lowTFcopyL), box.get_bottom(matrix.get(draw.indBo, 3, 0)),
array.min(sequence.lowTFcopyPI)))
box.set_top(matrix.get(draw.indBo, 3, 0), math.max(array.max(sequence.lowTFcopyH), box.get_top(matrix.get(draw.indBo, 3, 0)),
array.max(sequence.lowTFcopyPI)))
top := box.get_top (matrix.get(draw.indBo, 3, 0))
bottom := box.get_bottom(matrix.get(draw.indBo, 3, 0))
if typ == "Point Figure"
tick = (top - bottom) / 30
levels = array.new_float(), labels = array.new_label(), X1 = 1
for i = 0 to 29
array.push(levels, bottom + (tick * i))
for i = 0 to array.size(sequence.lowTFcopyC) - 1
for nxx = 0 to array.size(levels) - 1
if array.get(sequence.lowTFcopyC, i) >= array.get(sequence.lowTFcopyO, i)
if array.get(levels, nxx) >= array.get(sequence.lowTFcopyO, i) and array.get(levels, nxx) <= array.get(sequence.lowTFcopyC, i)
array.push(labels, label.new(
array.get(timeArray, array.size(timeArray) - X1) , array.get(levels, nxx),
color = color.lime, text = "X" , size = sz, textcolor = color.white,
xloc = xloc.bar_time, style = label.style_text_outline
))
else
if array.get(levels, nxx) <= array.get(sequence.lowTFcopyO, i) and array.get(levels, nxx) >= array.get(sequence.lowTFcopyC, i)
array.push(labels, label.new(array.get(timeArray, array.size(timeArray) - X1), array.get(levels, nxx),
color = color.red, text = "O" , size = sz, textcolor = color.white,
xloc = xloc.bar_time, style = label.style_text_outline
))
X1 += 2
for i = 0 to array.size(draw.priceBox) - 1
box.delete(array.shift(draw.priceBox))
trueAvg = math.round((bar_index - array.indexof(timeArray, left)) / 2)
label.new(array.get(timeArray, array.size(timeArray) - trueAvg), top,
typ + " " + (((close / close[1] - 1) * 100) >= 0 ? "+" : "") +
str.tostring((close / close[1] - 1) * 100, format.percent) + " "
+ str.tostring(volume, format.volume), color = #ffffff00,
textcolor = color.white, xloc = xloc.bar_time
)
if hideInd2 == false
calcB1 = (math.round(right - left) / 3), altY = (top - bottom) / 3, ind1Box = box.new(
bar_index + 10, top,
math.min(bar_index + 30, bar_index + 10 + array.size(sequence.lowTFcopyC)),
top - altY , bgcolor = color.new(color.blue, 95), border_color = na)
//array.reverse(sequence.lowTFcopyI1),
tempArray1 = array.new_float()
funcAppend(sequence.lowTFcopyI1, tempArray1, box.get_bottom(ind1Box) * 1.0001, ind1Box, draw.indLi, ind1, 0, ind1Col)
funcDraw(ind1Box, draw.indLa, draw.indLi, tempArray1, ind1Len, ind1, box.get_bottom(ind1Box), 0)
label.set_y(matrix.get(draw.indLa, 0, 2), box.get_top(ind1Box) * 1.0001), ind2Box = box.new(
bar_index + 10, box.get_bottom(ind1Box),
math.min(bar_index + 30, bar_index + 10 + array.size(sequence.lowTFcopyC)),
top - (altY * 2), bgcolor = color.new(color.blue, 95), border_color = na)
//array.reverse(sequence.lowTFcopyI2),
tempArray2 = array.new_float()
funcAppend(sequence.lowTFcopyI2, tempArray2, box.get_bottom(ind2Box) * 1.0001, ind2Box, draw.indLi, ind2 , 1, ind2Col)
funcDraw(ind2Box, draw.indLa, draw.indLi, tempArray2, ind2Len, ind2, box.get_bottom(ind2Box), 1)
label.set_text(matrix.get(draw.indLa, 0, 0), label.get_text(matrix.get(draw.indLa, 0, 0)) + "\n" + label.get_text(matrix.get(draw.indLa, 1, 1)))
label.delete(matrix.get(draw.indLa, 1, 1)), ind3Box = box.new(
bar_index + 10, box.get_bottom(ind2Box),
math.min(bar_index + 30, bar_index + 10 + array.size(sequence.lowTFcopyC)),
bottom, bgcolor = color.new(color.blue, 95), border_color = na)
// array.reverse(sequence.lowTFcopyI3),
tempArray3 = array.new_float()
funcAppend(sequence.lowTFcopyI3, tempArray3, box.get_bottom(ind3Box) * 1.0001, ind3Box, draw.indLi, ind3, 2, ind3Col)
funcDraw(ind3Box, draw.indLa, draw.indLi, tempArray3, ind3Len, ind3, box.get_bottom(ind3Box), 2)
label.set_text(matrix.get(draw.indLa, 1, 0), label.get_text(matrix.get(draw.indLa, 1, 0)) + "\n" + label.get_text(matrix.get(draw.indLa, 2, 1)))
label.delete(matrix.get(draw.indLa, 2, 1)), box.new(
box.get_left(ind1Box), box.get_top(ind1Box),
box.get_right(ind1Box), box.get_bottom(ind3Box),
border_color = color.white, bgcolor = na)
matrix.set(draw.ratingColor, 0, 0, #801922), matrix.set(draw.ratingColor, 0, 1, #f7525f), matrix.set(draw.ratingColor, 0, 2, #faa1a4)
matrix.set(draw.ratingColor, 1, 0, #b22833), matrix.set(draw.ratingColor, 1, 1, #f77c80), matrix.set(draw.ratingColor, 1, 2, #fccbcd)
matrix.set(draw.ratingColor, 2, 0, #a5d6a7), matrix.set(draw.ratingColor, 2, 1, #66bb6a), matrix.set(draw.ratingColor, 2, 2, #58ff56)
matrix.set(draw.ratingColor, 3, 0, #81c784), matrix.set(draw.ratingColor, 3, 1, #388e3c), matrix.set(draw.ratingColor, 3, 2, #58ff56)
ratingi1 = -6, ratingi2 = -5
ratingi3 = 1, ratingi4 = 2
altY2 = (top - bottom) / 4
for i = 0 to 2
calcCond = math.round(array.get(sequence.lowTFcopyR, array.size(sequence.lowTFcopyR) - 1) * 10)
cond = calcCond == ratingi1, cond1 = calcCond == ratingi2, cond2 = calcCond == ratingi3, cond3 = calcCond == ratingi4
matrix.set(draw.indBo, 4, i, box.new(array.get(timeArray, array.indexof(timeArray, left) - 2),
bottom + (altY2 * i), left, bottom + (altY2 * (i + 1)),
bgcolor = color.new(matrix.get(draw.ratingColor, 1, i), cond ? 25 : 60),
xloc = xloc.bar_time, border_color = color.white,
text = str.tostring(ratingi2) + (cond1 ? "◉" : ""),
text_color = color.white, text_size = size.small
))
matrix.set(draw.indBo, 5, i, box.new(array.get(timeArray, array.indexof(timeArray, left) - 4),
bottom + (altY2 * i),
array.get(timeArray, array.indexof(timeArray, left) - 2), bottom + (altY2 * (i + 1)),
bgcolor = color.new(matrix.get(draw.ratingColor, 0, i), cond1 ? 25 : 60),
xloc = xloc.bar_time, border_color = color.white, text = str.tostring(ratingi1) + (cond ? "◉" : ""),
text_color = color.white, text_size = size.small
))
matrix.set(draw.indBo, 6, i, box.new(bar_index + 1, top - (altY2 * (i + 1)), bar_index + 3 ,
top - (altY2 * (i + 2)),
bgcolor = color.new(matrix.get(draw.ratingColor, 2, i), cond ? 25 : 60) ,
xloc = xloc.bar_index, border_color = color.white, text = str.tostring(ratingi3) + (cond2 ? "◉" : ""),
text_color = color.white, text_size = size.small
))
matrix.set(draw.indBo, 7, i, box.new(bar_index + 3, top - (altY2 * (i + 1)),
bar_index + 5 , top - (altY2 * (i + 2)),
bgcolor = color.new(matrix.get(draw.ratingColor, 3, i), cond ? 25 : 60),
xloc = xloc.bar_index, border_color = color.white, text = str.tostring(ratingi4) + (cond3 ? "◉" : ""),
text_color = color.white, text_size = size.small))
ratingi1 += 2 , ratingi2 += 2, ratingi3 += 2, ratingi4 += 2
matrix.set(draw.indLa, 7, 0, label.new(array.get(timeArray, array.indexof(timeArray, left) - 2),
top - altY2, text = "−", textcolor = color.white, color = #ffffff00, xloc = xloc.bar_time, size = size.large))
matrix.set(draw.indLa, 7, 1, label.new(bar_index + 3,
top - altY2, text = "+", textcolor = color.white, color = #ffffff00, xloc = xloc.bar_index,size = size.large))
r5 =
array.indexof(timeArray, box.get_left(matrix.get(draw.indBo, 5, 0))) -
array.indexof(timeArray, box.get_right(pricexvolGraph)), r6 = math.round(r5/2), bCond = false
if r5 > 100
bCond := true
if box.get_right(pricexvolGraph) >= array.get(timeArray, array.indexof(timeArray, box.get_left(matrix.get(draw.indBo, 5, 0))) - 7) or bCond == true
setLeftRight(pricexvolGraph, line(na), label(na), "Box", -r6, bCond)
setLeftRight(box(na), matrix.get(draw.indLi, 6, 1), label(na), "Line", -r6, bCond)
for i = 0 to 7
setLeftRight(box(na), line(na), matrix.get(draw.indLa, 6, i), "Label", -r6, bCond)
if i <= 3
setLeftRight(matrix.get(draw.indBo, 0, i), line(na), label(na), "Box", -r6, bCond)
for i = 0 to array.size(draw.numLi) - 1
setLeftRight(box(na), array.get(draw.numLi, i), label(na), "Line", -r6, bCond)
for i = 0 to array.size(draw.numLa) - 1
setLeftRight(box(na), line(na), array.get(draw.numLa, i), "Label", -r6, bCond)
|
TCG AI Tools | https://www.tradingview.com/script/bMgC2kIS-TCG-AI-Tools/ | TheChartGuys | https://www.tradingview.com/u/TheChartGuys/ | 249 | 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('TCG AI Tools')
// Rule 1: Price trend
long_ema = ta.sma(close, 10)
short_ema = ta.sma(close, 20)
trend = short_ema > long_ema ? 1 : 0
// Plotting the trend indicator as a line on the chart
trend_color = trend == 1 ? color.red : color.green
plot(0, color=trend_color, style=plot.style_line, linewidth=40)
price = input(close, title='Price')
bb_length = input(20, title='Bollinger length')
bb_multiplier = input(2, title='Bollinger Multiplier')
// BB
bb_basis = ta.sma(price, bb_length)
bb_dev = bb_multiplier * ta.stdev(price, bb_length)
bb_upper = bb_basis + bb_dev
bb_lower = bb_basis - bb_dev
// Plots
bbc = ta.crossover(price, bb_upper) ? float(0) : float(na)
plotshape(bbc, title='BB Cross', style=shape.triangledown, color=color.rgb(255, 105, 105), size=size.normal, location=location.absolute)
bbd = ta.crossover(price, bb_lower) ? float(0) : float(na)
plotshape(bbd, title='BB Cross', style=shape.triangleup, color=color.rgb(97, 255, 103), size=size.normal, location=location.absolute)
//RSI Overbought. Green and Red Background & Blue/Purple bars
inp_overbought = input.int(defval=70, title='Overbought', minval=1)
inp_oversold = input.int(defval=30, title='Oversold', minval=1)
src = close
len = input.int(14, minval=1, title='Length')
up = ta.rma(math.max(ta.change(src), 0), len)
down = ta.rma(-math.min(ta.change(src), 0), len)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - 100 / (1 + up / down)
//Overbought
overbought = rsi >= inp_overbought ? color.new(color.green, 40) : na
overboughtcol = rsi >= inp_overbought ? color.rgb(156, 39, 176) : na
bgcolor(overbought)
//barcolor(overboughtcol)
//Oversold
oversold = rsi <= inp_oversold ? color.new(color.red, 40) : na
oversoldcol = rsi <= inp_oversold ? color.blue : na
bgcolor(oversold)
//barcolor(oversoldcol) |
Recursive Zigzag [Trendoscope] | https://www.tradingview.com/script/J6mxhxdn-Recursive-Zigzag-Trendoscope/ | Trendoscope | https://www.tradingview.com/u/Trendoscope/ | 1,260 | study | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © Trendoscope Pty Ltd
// ░▒
// ▒▒▒ ▒▒
// ▒▒▒▒▒ ▒▒
// ▒▒▒▒▒▒▒░ ▒ ▒▒
// ▒▒▒▒▒▒ ▒ ▒▒
// ▓▒▒▒ ▒ ▒▒▒▒▒▒▒▒▒▒▒
// ▒▒▒▒▒▒▒▒▒▒▒ ▒ ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
// ▒ ▒ ░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░▒▒▒▒▒▒▒▒
// ▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ▒▒
// ▒▒▒▒▒ ▒▒▒▒▒▒▒
// ▒▒▒▒▒▒▒▒▒
// ▒▒▒▒▒ ▒▒▒▒▒
// ░▒▒▒▒ ▒▒▒▒▓ ████████╗██████╗ ███████╗███╗ ██╗██████╗ ██████╗ ███████╗ ██████╗ ██████╗ ██████╗ ███████╗
// ▓▒▒▒▒ ▒▒▒▒ ╚══██╔══╝██╔══██╗██╔════╝████╗ ██║██╔══██╗██╔═══██╗██╔════╝██╔════╝██╔═══██╗██╔══██╗██╔════╝
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ██║ ██████╔╝█████╗ ██╔██╗ ██║██║ ██║██║ ██║███████╗██║ ██║ ██║██████╔╝█████╗
// ▒▒▒▒▒ ▒▒▒▒▒ ██║ ██╔══██╗██╔══╝ ██║╚██╗██║██║ ██║██║ ██║╚════██║██║ ██║ ██║██╔═══╝ ██╔══╝
// ▒▒▒▒▒ ▒▒▒▒▒ ██║ ██║ ██║███████╗██║ ╚████║██████╔╝╚██████╔╝███████║╚██████╗╚██████╔╝██║ ███████╗
// ▒▒ ▒
//@version=5
import HeWhoMustNotBeNamed/DrawingTypes/2 as dr
import HeWhoMustNotBeNamed/DrawingMethods/2
import HeWhoMustNotBeNamed/ZigzagTypes/5 as zg
import HeWhoMustNotBeNamed/ZigzagMethods/6
import HeWhoMustNotBeNamed/utils/1 as ut
import HeWhoMustNotBeNamed/RecursiveAlerts/2 as ra
import HeWhoMustNotBeNamed/iLogger/1 as l
indicator("Recursive Zigzag [Trendoscope]", "RZigzag[Trendoscope]", overlay = true, max_lines_count=500, max_labels_count=500, max_bars_back = 1000)
theme = input.string('Dark', title='Theme', options=['Light', 'Dark'], group='Generic Settings',
tooltip='Chart theme settings. Line and label colors are generted based on the theme settings. If dark theme is selected, '+
'lighter colors are used and if light theme is selected, darker colors are used.')
// var logger = l.Logger.new(pageSize=20)
// logger.init()
zigzagLength = input.int(5, step=5, minval=3, title='Length', group='Zigzag', tooltip='Zigzag length for level 0 zigzag')
depth = input.int(200, "Depth", step=25, maxval=500, group='Zigzag', tooltip='Zigzag depth refers to max number of pivots to show on chart')
highlight = input.int(3, "Highlight Level", group='Zigzag', minval = 0, tooltip = 'Highlight one level of the zigzag out of the available')
useRealTimeBars = input.bool(true, 'Use Real Time Bars', group='Zigzag', tooltip = 'If enabled real time bars are used for calculation. Otherwise, only confirmed bars are used')
enableRsi = input.bool(true, 'RSI', group='Indicators', inline='rsi')
rsiLength = input.int(14, '', group='Indicators', inline='rsi', tooltip='Enable and configure RSI indicator')
enableMfi = input.bool(true, 'MFI', group='Indicators', inline='mfi')
mfiLength = input.int(14, '', group='Indicators', inline='mfi', tooltip='Enable and configure MFI indicator')
enableObv = input.bool(true, 'OBV', group='Indicators', inline='obv', tooltip = 'Enable and configure OBV indicator')
enableCustom = input.bool(false, '', group='Custom External Indicator', inline='custom')
customName = input.string('Custom', '', group='Custom External Indicator', inline='custom')
customValue = input.source(close, '', group='Custom External Indicator', inline='custom', tooltip = 'Enable and configure custom external indicator')
showLabel = false
alertTooltip = 'Confirmed Pivot refers to last but one pivot which is confirmed. Alerting on confirmed pivot means alerts are triggered only when a new confirmed pivot is formed. '+
'This also means there will be lag in the alert. On the contry, if you select Last Pivot Update alerts will be on real time. But, remember that last pivot of the Zigzag always repaint. Hence, there will be lots of alerts and repaints'
alertType = input.string('Confirmed Pivot Update', 'Alert Type', ['Confirmed Pivot Update', 'Last Pivot Update'], tooltip = alertTooltip, group='Alert')
alertPivot = alertType == 'Confirmed Pivot Update'? 1 : 0
defaultAlertTemplate = '{
\n\t"type" : "{alertType}",
\n\t"level": "{level}",
\n\t"pivot" : {pivot}
\n}'
alertTemplate = input.text_area (defaultAlertTemplate, '', group='Alert', display=display.none)
offset = useRealTimeBars? 0 : 1
indicators = matrix.new<float>()
indicatorNames = array.new<string>()
if(enableRsi)
indicatorNames.unshift('RSI'+str.tostring(rsiLength))
indicators.add_row(0, array.from(ta.rsi(high, rsiLength), ta.rsi(low, rsiLength), ta.rsi(close, rsiLength)))
showLabel := true
if(enableMfi)
indicatorNames.unshift('MFI'+str.tostring(mfiLength))
indicators.add_row(0, array.from(ta.mfi(high, mfiLength), ta.mfi(low, mfiLength), ta.mfi(close, mfiLength)))
showLabel := true
if(enableObv)
indicatorNames.unshift('OBV')
indicators.add_row(0, array.from(ta.obv, ta.obv, ta.obv))
if(enableCustom and customValue!=close)
indicatorNames.unshift(customName)
indicators.add_row(0, array.from(customValue, customValue, customValue))
themeColors = ut.getColors(theme)
var zg.Zigzag zigzag = zg.Zigzag.new(zigzagLength, depth, offset)
zigzag.calculate(array.from(high, low), indicators, indicatorNames)
var array<zg.ZigzagDrawing> drawingArray = array.new<zg.ZigzagDrawing>()
var firstDraw = true
var lastPivotBar = 0
if(barstate.islast and (firstDraw or zigzag.flags.newPivot))
drawingArray.clear()
firstDraw := false
mlzigzag = zigzag
rowNum = 0
var legend = table.new(position=position.top_right, columns=2, rows=100, border_width=1)
table.clear(legend, 0, 0, 1, 99)
while(mlzigzag.zigzagPivots.size() > 3)
labelColor = themeColors.remove(0)
themeColors.push(labelColor)
highlightLevel = rowNum == highlight
lineWidth = highlightLevel ? 2 : 0
lineStyle = highlightLevel ? line.style_solid:line.style_dotted
lineColor = highlightLevel ? labelColor : color.new(labelColor, 30)
zg.ZigzagProperties props = zg.ZigzagProperties.new(lineColor, lineWidth, lineStyle, highlightLevel, maxObjects = depth)
zg.ZigzagDrawing drawing = zg.ZigzagDrawing.new(mlzigzag, props)
drawing.drawplain()
drawingArray.push(drawing)
if(highlightLevel)
alertPivotPoint = mlzigzag.zigzagPivots.get(alertPivot)
if(lastPivotBar < alertPivotPoint.point.bar)
lastPivotBar := alertPivotPoint.point.bar
keys = array.from('{alertType}', '{level}', '{pivot}')
values = array.from(alertType, str.tostring(highlight), alertPivotPoint.tostring())
currentAlert = ra.updateAlertTemplate(alertTemplate, keys, values)
alert(currentAlert, alert.freq_once_per_bar_close)
table.cell(legend, 0, rowNum, 'Level'+str.tostring(rowNum), text_color=lineColor,
bgcolor=color.new(labelColor, highlightLevel? 90 : 50),
text_size = highlightLevel?size.normal : size.small)
mlzigzag := mlzigzag.nextlevel()
rowNum+=1 |
Diff_US10Y_US02Y | https://www.tradingview.com/script/N9AKsyNt-Diff-US10Y-US02Y/ | easonoic | https://www.tradingview.com/u/easonoic/ | 7 | 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/
// © easonoic
//@version=5
indicator("Diff_US10Y_US02Y", overlay=true)
US02Y = input.symbol("US02Y", "Symbol")
US10Y = input.symbol("US10Y", "Symbol")
us2y_s_o = request.security(US02Y, 'D', open)
us10y_s_o = request.security(US10Y, 'D', open)
us2y_s_c = request.security(US02Y, 'D', close)
us10y_s_c = request.security(US10Y, 'D', close)
us2y_s_high = request.security(US02Y, 'D', high)
us10y_s_high = request.security(US10Y, 'D', high)
us2y_s_low = request.security(US02Y, 'D', low)
us10y_s_low = request.security(US10Y, 'D', low)
US10Y_US02Y_diff_o = us10y_s_o - us2y_s_o
US10Y_US02Y_diff_c = us10y_s_c - us2y_s_c
US10Y_US02Y_diff_high = us10y_s_high - us2y_s_high
US10Y_US02Y_diff_low = us10y_s_low - us2y_s_low
bool upBar = US10Y_US02Y_diff_c > US10Y_US02Y_diff_o
plotcandle(US10Y_US02Y_diff_o, US10Y_US02Y_diff_high, US10Y_US02Y_diff_low, US10Y_US02Y_diff_c, title='Diff_US10Y_US03Y', color = US10Y_US02Y_diff_o > US10Y_US02Y_diff_c ? color.green : color.red, wickcolor=color.black)
plot(US10Y_US02Y_diff_o, color=color.red, linewidth=2)
plot(0) |
Grenblatt Magic Formula | https://www.tradingview.com/script/o1pxojs2/ | formy76 | https://www.tradingview.com/u/formy76/ | 33 | 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/
//
//
// This is a rough version of the Return on Capital Employed
//@version=4
study("Magic Formula", precision=2)
var ebit_ttm = float(na)
var ebit_q1 = 0.0
var ebit_q2 = 0.0
var ebit_q3 = 0.0
var ebit_q4 = 0.0
ebit_series_filled = financial(syminfo.tickerid, "EBIT", "FQ", false)
ebit_series_fq = financial(syminfo.tickerid, "EBIT", "FQ", true)
ebit_series_fy = financial(syminfo.tickerid, "EBIT", "FY", false)
if not na(ebit_series_fq[0])
ebit_q4 := ebit_q3
ebit_q3 := ebit_q2
ebit_q2 := ebit_q1
ebit_q1 := ebit_series_fq[0]
ebit_ttm := ebit_q1 + ebit_q2 + ebit_q3 + ebit_q4
else if na(ebit_series_filled[0]) and not na(ebit_series_fy[0])
ebit_ttm := ebit_series_fy[0]
cur_assets = na(financial(syminfo.tickerid, "TOTAL_CURRENT_ASSETS", "FQ")) ? financial(syminfo.tickerid, "TOTAL_CURRENT_ASSETS", "FY") : financial(syminfo.tickerid, "TOTAL_CURRENT_ASSETS", "FQ")
cur_liabilities = na(financial(syminfo.tickerid, "TOTAL_CURRENT_LIABILITIES", "FQ")) ? financial(syminfo.tickerid, "TOTAL_CURRENT_LIABILITIES", "FY") : financial(syminfo.tickerid, "TOTAL_CURRENT_LIABILITIES", "FQ")
cash_stinv = na(financial(syminfo.tickerid, "CASH_N_SHORT_TERM_INVEST", "FQ")) ? financial(syminfo.tickerid, "CASH_N_SHORT_TERM_INVEST", "FY") : financial(syminfo.tickerid, "CASH_N_SHORT_TERM_INVEST", "FQ")
st_debt = na(financial(syminfo.tickerid, "SHORT_TERM_DEBT", "FQ")) ? financial(syminfo.tickerid, "SHORT_TERM_DEBT", "FY") : financial(syminfo.tickerid, "SHORT_TERM_DEBT", "FQ")
ppe = na(financial(syminfo.tickerid, "PPE_TOTAL_NET", "FQ")) ? financial(syminfo.tickerid, "PPE_TOTAL_NET", "FY") : financial(syminfo.tickerid, "PPE_TOTAL_NET", "FQ")
debt = na(financial(syminfo.tickerid, "TOTAL_DEBT", "FQ")) ? financial(syminfo.tickerid, "TOTAL_DEBT", "FY") : financial(syminfo.tickerid, "TOTAL_DEBT", "FQ")
min_interest = na(financial(syminfo.tickerid, "MINORITY_INTEREST", "FQ")) ? financial(syminfo.tickerid, "MINORITY_INTEREST", "FY") : financial(syminfo.tickerid, "MINORITY_INTEREST", "FQ")
cash = na(financial(syminfo.tickerid, "CASH_N_EQUIVALENTS", "FQ")) ? financial(syminfo.tickerid, "CASH_N_EQUIVALENTS", "FY") : financial(syminfo.tickerid, "CASH_N_EQUIVALENTS", "FQ")
tot_shares = na(financial(syminfo.tickerid, "TOTAL_SHARES_OUTSTANDING", "FQ")) ? financial(syminfo.tickerid, "TOTAL_SHARES_OUTSTANDING", "FY") : financial(syminfo.tickerid, "TOTAL_SHARES_OUTSTANDING", "FQ")
capital_employed = max(0 , ((cur_assets[0]-cash_stinv[0]) - (cur_liabilities[0]-st_debt))) + ppe[0]
roc = (ebit_ttm / capital_employed)*100
mkt_cap = tot_shares * close
ev = mkt_cap + debt + min_interest - cash
earnings_yield = (ebit_ttm / ev)*100
c = if roc >= 25
color.new(color.green, 75)
else if roc > 0
color.new(color.yellow, 75)
else
color.new(color.red, 75)
plot(roc, color=c, style=plot.style_area, histbase=0)
plot(earnings_yield, linewidth=2)
|
[CLX] Library Motion - Examples | https://www.tradingview.com/script/KiuwdJVY/ | cryptolinx | https://www.tradingview.com/u/cryptolinx/ | 12 | 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/
// © cryptolinx
//@version=5
indicator('[CLX] Motion - Examples', overlay = true)
import cryptolinx/Motion/11 as motion
// var table exTable = table.new(position=position.middle_center, columns=1, rows=4, border_width=1)
// varip kf_0 = m.keyframe.new(intv = 1, steps = 2)
// string content_0 = m.marquee(kf_0, 'marquee', _ws = 10)
// table.cell(exTable, 0, 0, kf_0.output, width = 50, text_color = color.white, bgcolor = color.maroon)
// varip kf_1 = m.keyframe.new(intv = 1), m.blink(kf_1, 'blink')
// table.cell(exTable, 0, 1, kf_1.output, width = 50, text_color = color.white, bgcolor = color.blue)
// varip kf_2 = m.keyframe.new(intv = 1), m.slideInLeft(kf_2, 'slide in left')
// table.cell(exTable, 0, 2, kf_2.output, width = 50, text_color = color.white, bgcolor = color.orange)
// varip kf_3 = m.keyframe.new(intv = 1), m.slideInRight(kf_3, 'slide in right')
// table.cell(exTable, 0, 3, kf_3.output, width = 50, text_color = color.white, bgcolor = color.aqua)
// ------------------------------------------------------------------------------------------------
/// ———— User Input {
//
// ⚠️ IMPORTANT: Example Type. NOT REQUIRED.
//
type user_input
// --
string fx
bool play
string timing
int intv
int mu
int step
bool reset
int max_loops
int sub_start
int sub_length
bool ltr
bool refill
string prefix
string txt
int ws
string suffix
int color_steps
bool color_cycle
color color_from
color color_to
string mode_start
int mode_calc
// --
var __settings = user_input.new(
fx = input.string('marquee', 'Transition', options = ['marquee', 'blink', 'blend_in_right', 'blend_out_right', 'blend_in_left', 'blend_out_left', 'slide_in_left', 'slide_in_right', 'slide_out_left', 'slide_out_right'], group = 'ACTION'),
play = input.bool(true, 'Play', group = 'ACTION'),
timing = input.string('on_time', 'Event Producer', options = ['on_tick', 'on_time', 'on_index'], group = 'TIMING'),
intv = input.int(1, title = 'Interval (Δt)', step = 1, minval = 1, maxval = 100, tooltip = 'Delta Time [1;∞[', group = 'TIMING'),
mu = input.int(1000, title = 'onTime - Fineness (μ)', step = 50, minval = 50, maxval = 2000, tooltip = '[50-2000] 1000 = default. lower value = higher freq.', group = 'TIMING'),
step = input.int(1, title = 'Steps Per Execution', step = 1, minval = 1, maxval = 20, group = 'PREFERENCES'),
reset = input.bool(false, title = 'Reset On Every Bar', group = 'PREFERENCES'),
max_loops = input.int(0, title = 'Max. Loops', step = 1, minval = 0, maxval = 100, tooltip = '0 = infinite', group = 'PREFERENCES'),
sub_start = input.int(0, title = 'Subsequence Start', step = 1, minval = 0, maxval = 20, tooltip = '[ABCDEF]GHI...\n| |\n0 5', group = 'PREFERENCES'),
sub_length = input.int(0, title = 'Subsequence Length', step = 1, minval = 0, maxval = 20, group = 'PREFERENCES'),
refill = input.bool(true, 'Placeholder String', group = 'PREFERENCES', tooltip = 'true = default; false = slide effect without placeholder (+/- string length)'),
ltr = input.bool(false, title = 'Left To Right', group = 'ONLY MARQUEE'),
prefix = input.string('', 'Prefix', group = 'CONTENT'),
txt = input.string('ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789', 'Text', group = 'CONTENT'),
ws = input.int(0, title = 'Trailing White Space', step = 1, minval = 0, maxval = 10, group = 'CONTENT'),
suffix = input.string('', 'Suffix', group = 'CONTENT'),
color_steps = input.int(6, title = 'Gradient Steps', step = 1, minval = 1, maxval = 20, group = 'COLOR'),
color_cycle = input.bool(true, title = 'Color Cycle', group = 'COLOR'),
color_from = input.color(color.rgb(0, 57, 212), 'Color From', group = 'COLOR'),
color_to = input.color(color.rgb(59, 209, 255), 'Color To', group = 'COLOR'),
mode_start = 'now', // input.string('now', 'Effect Start', options = ['now', 'on_open', 'on_close'], group = 'ADVANCED/DEVELOPMENT'),
mode_calc = 1) // input.int(1, 'Calculation Mode', minval = 0, maxval = 1, step = 1, tooltip = '0 = relative; 1 = absolute', group = 'ADVANCED/DEVELOPMENT'))
// }
// ———— Motion 🪄 {
//
// ⚠️ IMPORTANT: The keyframe object must be created by using the `varip` keyword.
//
varip transitionKf = motion.keyframe.new(intv = __settings.intv, steps = __settings.step, execution = __settings.play) // create keyframe
string transitionString = motion.transition(transitionKf, _seq = __settings.txt, _fx = __settings.fx, _ws = __settings.ws, _maxLoops = __settings.max_loops,
_subLen = __settings.sub_length, _subStart = __settings.sub_start, _ltr = __settings.ltr, _resetOnEveryBar = __settings.reset, _autoplay = __settings.play,
_refill = __settings.refill, _timerType = __settings.timing, _timerMu = __settings.mu, _timerMode = __settings.mode_calc, _prefix = __settings.prefix, _suffix = __settings.suffix)
// --
varip iterationKf = motion.keyframe.new(intv = 3, steps = __settings.step, execution = __settings.play)
motion.iteration(iterationKf, _seqArr = array.from('THIS','IS','AN','ITERATION','EFFECT!'), _ws = __settings.ws,
_subLen = __settings.sub_length, _subStart = __settings.sub_start, _ltr = __settings.ltr, _resetOnEveryBar = __settings.reset, _autoplay = false, //__settings.play,
_refill = __settings.refill, _timerType = __settings.timing, _timerMu = __settings.mu, _timerMode = __settings.mode_calc, _prefix = __settings.prefix, _suffix = __settings.suffix)
// --
varip colorKf = motion.keyframe.new(intv = __settings.intv, steps = __settings.step, execution = __settings.play)
color gradient = motion.color_gradient(colorKf, __settings.color_from, __settings.color_to, _steps = __settings.color_steps, _cycle = __settings.color_cycle, _timerType = __settings.timing)
// }
// ———— Label {
//
var select = label.new(bar_index, 750, text = 'Double click, to select a transition effect from input:', textcolor = color.white, color = #ffffff0b, size = size.normal, style = label.style_label_center)
var fx = label.new(bar_index, 700, text = __settings.fx, textcolor = #AAFF00, color = #ffffff0b, size = size.normal, style = label.style_label_center, textalign = text.align_center, text_font_family = font.family_default)
var openSource = label.new(bar_index, 300, text = 'open 💙 source', textcolor = color.white, color = #ffffff0b, size = size.normal, style = label.style_label_center)
var example = label.new(bar_index, 600, text = '', textcolor = color.white, color = #ffffff0b, size = size.huge, style = label.style_label_center, textalign = text.align_center, text_font_family = font.family_monospace)
var itr = label.new(bar_index, 450, text = '', textcolor = color.white, color = #ffffff0b, size = size.normal, style = label.style_label_center, textalign = text.align_center, text_font_family = font.family_monospace)
// --
label.set_x(select, bar_index), label.set_x(fx, bar_index), label.set_x(example, bar_index), label.set_x(openSource, bar_index), label.set_x(itr, bar_index),
label.set_text(fx, __settings.fx), label.set_text(example, transitionString), label.set_text(itr, iterationKf.output)
label.set_textcolor(itr, gradient)
// }
// ------------------------------------------------------------------------------------------------
// ———— Simple Animated Logo/Tag Idea {
//
renderLogo(string _tagline, string _sizeLogo = size.huge, string _sizeTag = size.normal, color _colorLogo = #ff5252, color _colorTag = #ffffff96, _colorDecor = #ff525234, int _x = bar_index, float _y = 1000) =>
// >>
array.from(
label.new(_x, _y, text = '', size = _sizeLogo, color = #00000000, textcolor = _colorLogo, text_font_family = font.family_default, style = label.style_label_center, textalign = text.align_center),
label.new(_x, _y, text = '└', size = _sizeLogo, color = #00000000, textcolor = _colorDecor, text_font_family = font.family_default, style = label.style_label_upper_right, textalign = text.align_left),
label.new(_x, _y, text = '┘', size = _sizeLogo, color = #00000000, textcolor = _colorDecor, text_font_family = font.family_default, style = label.style_label_upper_left, textalign = text.align_left),
label.new(_x, _y, text = '┌', size = _sizeLogo, color = #00000000, textcolor = _colorDecor, text_font_family = font.family_default, style = label.style_label_lower_right, textalign = text.align_left),
label.new(_x, _y, text = '┐', size = _sizeLogo, color = #00000000, textcolor = _colorDecor, text_font_family = font.family_default, style = label.style_label_lower_left, textalign = text.align_left),
label.new(_x, _y, text = ' ', size = _sizeLogo, color = #00000000, textcolor = color.new(_colorLogo, 75), text_font_family = font.family_default, style = label.style_label_down, textalign = text.align_left),
label.new(_x, _y, text = '\n\n\n\n' + _tagline, size = _sizeTag, color = #00000000, textcolor = _colorTag, text_font_family = font.family_monospace, style = label.style_label_up, textalign = text.align_left))
// }
// ———— Update Logo {
//
update(array <label> _logo, string _textLogo, string _textTagline, int _x = bar_index, float _y = 1000) =>
// --
if barstate.islast
for i = 0 to array.size(_logo) - 1
label.set_xy(array.get(_logo, i), _x, _y)
label.set_text(array.get(_logo, 0), _textLogo)
label.set_text(array.get(_logo, 6), _textTagline)
// >>
// void
// }
// ———— Motion 🪄 {
//
varip logoKf = motion.keyframe.new(1, 7)
string marquee = motion.transition(logoKf, _fx = 'marquee', _seq = 'M◞TION.M◟TION.M◜TION.M◝TION.', _subLen = 7)
varip taglineKf = motion.keyframe.new(4, 1)
motion.iteration(taglineKf, _seqArr = array.from('Showcase','Library'), _refill = true)
// --
var array <label> LOGO = renderLogo('- A Pine Script™ Showcase -', size.huge)
update(LOGO, marquee, '\n\n\n\n' + '- A Pine Script™ ' + taglineKf.output + ' -')
// }
// # EOF |
Engulfing Pinbar [serkany88] | https://www.tradingview.com/script/EN4zmIA6-Engulfing-Pinbar-serkany88/ | serkany88 | https://www.tradingview.com/u/serkany88/ | 460 | 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/
// © serkany88
//@version=5
indicator("Englulfing Pinbar [serkany88]", shorttitle = "Engulfing Pinbar", overlay=true, max_boxes_count=500)
//Inputs
Wicksize = input.float(defval= 30, title= "Wick Engulf Size %", minval = 1, maxval= 90, tooltip= "Top or Bottom Wick size compared to body of the candle. Recommended to keep it around at least 50% for below 15M timeframes and around 30% for 30M and above timeframes.")
oppositeWick = input.float(defval=60, title="Opposite Wick Filter %", minval= 1, maxval= 100, tooltip ="The filter of opposite wick size as percentage, higher values means more relaxed detection.")
colorbars = input.bool(true, title="Color Detected Bars")
//Static Vars
topWickSize = math.abs (math.max( close, open) - high)
bottomWickSize = math.abs (math.min( close, open) - low)
bodySize = math.abs ( close -open)
//Functions for Engulfing Pinbars
bullEngulfPinbar(float minRejectWick = 50.0, bool mustEngulfWick = true) =>
rejectionRule = minRejectWick == 0.0 or (bottomWickSize / bodySize >= (minRejectWick / 100) and topWickSize / bodySize < (oppositeWick / 100))
result = close[1] <= open[1] and close >= open[1] and open <= close[1] and rejectionRule and (not mustEngulfWick or (close >= high[1] and low < low[1])) and bodySize > 0
bearEngulfPinbar(float minRejectWick = 50.0, bool mustEngulfWick = true) =>
rejectionRule = minRejectWick == 0.0 or (topWickSize / bodySize >= (minRejectWick / 100) and bottomWickSize / bodySize < (oppositeWick / 100))
result = close[1] >= open[1] and close <= open[1] and open >= close[1] and rejectionRule and (not mustEngulfWick or (close <= low[1] and high > high[1])) and bodySize > 0
// et Variables
bulldetected = bullEngulfPinbar(Wicksize, true)
beardetected = bearEngulfPinbar(Wicksize, true)
//HTF DETECTIONS AND DRAWINGS
enableHTF = input.bool(false, title="Enable HTF Checks", tooltip="Also checks higher time frame conditions and draws on your chart as boxes if enabled.", group="Higher TF")
htf = input.timeframe('', 'Higher Time Frame', group="Higher TF")
thickWick = true
ascColor = color.green
descColor = color.red
ctfCandleDeltaTime() =>
if timeframe.isseconds
timeframe.multiplier * 1000
else if timeframe.isminutes
timeframe.multiplier * 1000 * 60
else if timeframe.isdaily
timeframe.multiplier * 1000 * 60 * 1440
else if timeframe.isweekly
timeframe.multiplier * 1000 * 60 * 1440 * 7
else if timeframe.ismonthly
timeframe.multiplier * 1000 * 60 * 1440 * 30
else
0
var bodies = array.new_box()
var wicks = array.new_box()
var color bodyColor = na
var color wickColor = na
[htfO, htfH, htfL, htfC, htfOpenTime, htfCloseTime, htfbull, htfbear] = request.security(syminfo.tickerid, htf, [open, high, low, close, time, time_close, bullEngulfPinbar(Wicksize, true), bearEngulfPinbar(Wicksize, true)])
if array.size(bodies) == 500 / 2
box.delete(array.shift(bodies))
box.delete(array.shift(wicks))
bodyTop = math.max(htfO, htfC)
bodyBottom = math.min(htfO, htfC)
wickLeft = htfOpenTime + (htfCloseTime - htfOpenTime) / 2 - ctfCandleDeltaTime()
wickRight = htfCloseTime - (htfCloseTime - htfOpenTime) / 2 + ctfCandleDeltaTime() / 2
bodyColor := htfO > htfC ? color.new(descColor, 60) : htfO < htfC ? color.new(ascColor, 60) : bodyColor
wickColor := htfO > htfC ? color.new(descColor, 80) : htfO < htfC ? color.new(ascColor, 80) : wickColor
if enableHTF and (htfbull or htfbear)
array.push(bodies, box.new(htfOpenTime, bodyTop, htfCloseTime, bodyBottom, bodyTop == bodyBottom ? bodyColor : na, xloc=xloc.bar_time, bgcolor=bodyColor))
array.push(wicks, box.new(thickWick ? htfOpenTime : wickLeft, htfH, thickWick ? htfCloseTime : wickRight, htfL, na, xloc=xloc.bar_time, bgcolor=wickColor))
//Barcolor and Plots
barcolor(color = bulldetected and colorbars ? color.lime : beardetected and colorbars ? color.rgb(255, 0, 0) : na)
plotshape(bulldetected, title="Bull Pinbar Engulfing", style=shape.triangleup, location = location.belowbar, color=color.lime, size=size.small)
plotshape(beardetected, title="Bear Pinbar Engulfing", style=shape.triangledown, location = location.abovebar, color=color.rgb(255, 0, 0), size=size.small)
//Functional and Manual Alerts
if bulldetected or (enableHTF ? htfbull : false)
alert("Bullish Engulfing Pinbar Detected", alert.freq_once_per_bar_close)
if beardetected or (enableHTF ? htfbear : false)
alert("Bearish Engulfing Pinbar Detected", alert.freq_once_per_bar_close)
alertcondition(bulldetected or (enableHTF ? htfbull : false), "Bullish Engulfing Pinbar", "Bullish Engulfing Pinbar Detected")
alertcondition(beardetected or (enableHTF ? htfbear : false), "Bearish Engulfing Pinbar", "Bearish Engulfing Pinbar Detected") |
range_stat | https://www.tradingview.com/script/gwPMnVwj-range-stat/ | voided | https://www.tradingview.com/u/voided/ | 24 | 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/
// © voided
//@version=5
indicator("range_stat")
long = input(5, "long range length")
short = input(1, "short range length")
ma_len = input(5, "ma length")
l_rng = ta.highest(high, long) - ta.lowest(low, long)
s_rng = ta.highest(high, short) - ta.lowest(low, short)
pct = s_rng / l_rng
avg = ta.sma(pct, ma_len)
var float[] avgs = array.new<float>()
array.push(avgs, avg)
mu = array.avg(avgs)
stdev = array.stdev(avgs)
plot(avg)
plot(mu, color = color.red)
plot(mu + 2 * stdev, color = color.fuchsia)
plot(mu - 2 * stdev, color = color.fuchsia)
|
RS: Footprint | https://www.tradingview.com/script/HJKrMMlp-RS-Footprint/ | RunStrat | https://www.tradingview.com/u/RunStrat/ | 1,371 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © RunStrat
//@version=5
indicator("RS: Footprint", "RS: FP", max_labels_count = 500, max_lines_count = 50, max_bars_back=0, overlay = true)
mode_input = input.string("Delta", "Mode", ["Bid vs Ask", "Delta"])
ticks_input = input.int(1, "Ticks per step", minval = 1)
color_up_1_input = input.color(defval = color.new(#8d8d8d, 0), title = "Up 1", group = "Colors")
color_up_2_input = input.color(defval = color.new(#6b8bb6, 0), title = "Up 2", group = "Colors")
color_up_3_input = input.color(defval = color.new(#5289d3, 0), title = "Up 3", group = "Colors")
color_up_4_input = input.color(defval = color.new(#2e7de6, 0), title = "Up 4", group = "Colors")
color_up_5_input = input.color(defval = color.new(#0077ff, 0), title = "Up 5", group = "Colors")
color_dn_1_input = input.color(defval = color.new(#8d8d8d, 0), title = "Down 1", group = "Colors")
color_dn_2_input = input.color(defval = color.new(#b87b6c, 0), title = "Down 2", group = "Colors")
color_dn_3_input = input.color(defval = color.new(#d46d53, 0), title = "Down 3", group = "Colors")
color_dn_4_input = input.color(defval = color.new(#ec5732, 0), title = "Down 4", group = "Colors")
color_dn_5_input = input.color(defval = color.new(#fe3300, 0), title = "Down 5", group = "Colors")
color_v_1_input = input.color(defval = color.new(#636363, 0), title = "Volume 1", group = "Colors")
color_v_2_input = input.color(defval = color.new(#858585, 0), title = "Volume 2", group = "Colors")
color_v_3_input = input.color(defval = color.new(#a3a3a3, 0), title = "Volume 3", group = "Colors")
color_v_4_input = input.color(defval = color.new(#c9c9c9, 0), title = "Volume 4", group = "Colors")
color_v_5_input = input.color(defval = color.new(#ffffff, 0), title = "Volume 5", group = "Colors")
color_wick_input = input.color(defval = color.new(#666666, 0), title = "Candle wicks", group = "Colors")
PRICE_MAP_SIZE = 100000
BID_VS_ASK = 1
DELTA = 2
LABEL_POOL_SIZE = 500
LINE_POOL_SIZE = 50
var label[] label_pool = array.new_label()
var line[] line_pool = array.new_line()
var label[] labels_up = array.new_label()
var label[] labels_dn = array.new_label()
varip int[] prices_map = array.new_int(PRICE_MAP_SIZE)
varip float[] prices = array.new_float()
varip float[] sorted_prices = array.new_float()
varip float[] up_vol = array.new_float()
varip float[] dn_vol = array.new_float()
varip float prev_close = 0.0
varip float prev_volume = 0.0
varip bool at_ask = true
varip max_delta = 0.0
varip max_ask = 0.0
varip max_bid = 0.0
varip max_ask_bid = 0.0
varip max_tot_vol = 0.0
varip up = 0.0
varip dn = 0.0
mode = switch mode_input
"Bid vs Ask" => BID_VS_ASK
"Delta" => DELTA
if array.size(label_pool) == 0
for i = 1 to LABEL_POOL_SIZE
lbl = label.new(
bar_index,
close,
xloc = xloc.bar_index,
yloc = yloc.price,
color = color(na),
textcolor = color(na),
text_font_family = font.family_monospace)
array.push(label_pool, lbl)
if array.size(line_pool) == 0
for i = 1 to LINE_POOL_SIZE
ln = line.new(
bar_index,
close,
bar_index,
close,
xloc.bar_index,
extend.none,
color = color(na))
array.push(line_pool, ln)
step = ticks_input * syminfo.mintick
get_label() =>
lbl = array.shift(label_pool)
array.push(label_pool, lbl)
label.set_x(lbl, bar_index)
label.set_yloc(lbl, yloc.price)
label.set_text_font_family(lbl, font.family_monospace)
label.set_size(lbl, size.normal)
label.set_textcolor(lbl, color(na))
label.set_color(lbl, color(na))
lbl
get_line() =>
ln = array.shift(line_pool)
array.push(line_pool, ln)
line.set_x1(ln, bar_index)
line.set_x2(ln, bar_index)
ln
price_map_index(price) =>
int(math.round(price, 2) * 100 % PRICE_MAP_SIZE)
quantized_price(price) =>
price - price % step
vol_color(up, ratio) =>
if up
if ratio >= 0.8
color_up_5_input
else if ratio >= 0.5
color_up_4_input
else if ratio >= 0.3
color_up_3_input
else if ratio >= 0.1
color_up_2_input
else
color_up_1_input
else
if ratio >= 0.8
color_dn_5_input
else if ratio >= 0.5
color_dn_4_input
else if ratio >= 0.3
color_dn_3_input
else if ratio >= 0.1
color_dn_2_input
else
color_dn_1_input
diag_vol_color(up, ratio) =>
if up
if ratio >= 4
color_up_5_input
else if ratio >= 3
color_up_4_input
else if ratio >= 2
color_up_3_input
else if ratio >= 1.5
color_up_2_input
else
color_up_1_input
else
if ratio >= 4
color_dn_5_input
else if ratio >= 3
color_dn_4_input
else if ratio >= 2
color_dn_3_input
else if ratio >= 1.5
color_dn_2_input
else
color_dn_1_input
total_vol_color(ratio) =>
if ratio >= 1
color_v_5_input
else if ratio >= 0.9
color_v_4_input
else if ratio >= 0.7
color_v_3_input
else if ratio >= 0.3
color_v_2_input
else
color_v_1_input
render_delta_labels(price, d_vol, u_vol, max_delta, max_vol) =>
color_delta = vol_color(u_vol - d_vol >= 0, math.abs(u_vol - d_vol) / max_delta)
color_volume = total_vol_color((u_vol + d_vol) / max_vol)
lbl1 = get_label()
lbl2 = get_label()
label.set_text(lbl1, str.tostring(u_vol - d_vol))
label.set_y(lbl1, price)
label.set_textcolor(lbl1, color_delta)
label.set_style(lbl1, label.style_label_right)
label.set_text(lbl2, str.tostring(u_vol + d_vol))
label.set_y(lbl2, price)
label.set_textcolor(lbl2, color_volume)
label.set_style(lbl2, label.style_label_left)
render_bid_vs_ask_labels(price, d_vol, u_vol) =>
lbl1 = get_label()
lbl2 = get_label()
label.set_text(lbl1, str.tostring(d_vol))
label.set_y(lbl1, price)
label.set_textcolor(lbl1, color_dn_1_input)
label.set_style(lbl1, label.style_label_right)
label.set_text(lbl2, str.tostring(u_vol))
label.set_y(lbl2, price)
label.set_textcolor(lbl2, color_up_1_input)
label.set_style(lbl2, label.style_label_left)
array.push(labels_dn, lbl1)
array.push(labels_up, lbl2)
render_candle() =>
body_color = close >= open ? color_up_5_input: color_dn_5_input
ln1 = get_line()
ln2 = get_line()
ln3 = get_line()
line.set_y1(ln1, open)
line.set_y2(ln1, open == close ? close + (syminfo.mintick / 5) : close)
line.set_width(ln1, 3)
line.set_color(ln1, body_color)
line.set_y1(ln2, high)
line.set_y2(ln2, open > close ? open : close)
line.set_width(ln2, 1)
line.set_color(ln2, color_wick_input)
line.set_y1(ln3, low)
line.set_y2(ln3, close < open ? close : open)
line.set_width(ln3, 1)
line.set_color(ln3, color_wick_input)
get_price_index(price) =>
array.size(prices_map) > 0 ? array.get(prices_map, price_map_index(price)) : na
set_price_index(price, index) =>
if array.size(prices_map) > 0
array.set(prices_map, price_map_index(price), index)
if barstate.isrealtime
render_candle()
if barstate.isnew
up := 0
dn := 0
prev_volume := 0
max_delta := 0.0
max_ask := 0.0
max_bid := 0.0
max_ask_bid := 0.0
max_tot_vol := 0.0
prices_map := array.new_int(PRICE_MAP_SIZE)
if not barstate.isnew and prev_volume == 0
prev_volume := volume
diff = volume - prev_volume
prev_volume := volume
prev_close := prev_close != 0.0 ? prev_close : open
u_diff = 0.0
d_diff = 0.0
if close > prev_close
u_diff += diff
at_ask := true
if close < prev_close
d_diff += diff
at_ask := false
if close == prev_close
if at_ask
u_diff += diff
else
d_diff += diff
prev_close := close
up += u_diff
dn += d_diff
q_close = quantized_price(close)
price_index = get_price_index(q_close)
if na(price_index)
array.push(prices, q_close)
array.push(up_vol, u_diff)
array.push(dn_vol, d_diff)
price_index := array.size(prices) - 1
set_price_index(q_close, price_index)
if mode == BID_VS_ASK
array.push(sorted_prices, q_close)
array.sort(sorted_prices, order.descending)
else
array.set(up_vol, price_index, array.get(up_vol, price_index) + u_diff)
array.set(dn_vol, price_index, array.get(dn_vol, price_index) + d_diff)
u_vol = array.get(up_vol, price_index)
d_vol = array.get(dn_vol, price_index)
switch mode
BID_VS_ASK =>
max_ask := math.max(max_ask, u_vol)
max_bid := math.max(max_bid, d_vol)
label_idx = -1
for price in sorted_prices
idx = array.get(prices_map, price_map_index(price))
y = array.get(prices, idx)
u_vol := array.get(up_vol, idx)
d_vol := array.get(dn_vol, idx)
render_bid_vs_ask_labels(y, d_vol, u_vol)
if label_idx != -1
diag_ask_lbl = array.get(labels_up, label_idx)
diag_bid_lbl = array.get(labels_dn, label_idx + 1)
diag_ask = nz(str.tonumber(label.get_text(diag_ask_lbl))) + 0.0001
diag_bid = nz(str.tonumber(label.get_text(diag_bid_lbl))) + 0.0001
if diag_ask / max_ask >= 0.3
label.set_textcolor(diag_ask_lbl, diag_vol_color(true, diag_ask / diag_bid))
if diag_bid / max_bid >= 0.3
label.set_textcolor(diag_bid_lbl, diag_vol_color(false, diag_bid / diag_ask))
label_idx += 1
DELTA =>
max_delta := math.max(max_delta, math.abs(u_vol - d_vol))
max_tot_vol := math.max(max_tot_vol, u_vol + d_vol)
for idx = 0 to array.size(prices) - 1
y = array.get(prices, idx)
u_vol := array.get(up_vol, idx)
d_vol := array.get(dn_vol, idx)
render_delta_labels(y, d_vol, u_vol, max_delta, max_tot_vol)
delta = up - dn
up_percent = nz(math.round(100 * up / (up+dn)))
dn_percent = nz(math.round(100 * dn / (up+dn)))
lbl_info = get_label()
label.set_text(lbl_info, str.format("Δ: {0}\nV: ", delta) + str.tostring((up+dn), format.volume) + str.format("\n↓{0}% : ↑{1}%", dn_percent, up_percent))
label.set_y(lbl_info, high)
label.set_yloc(lbl_info, yloc.abovebar)
label.set_color(lbl_info, color.new(vol_color(delta > 0, math.abs(delta/(up+dn))), 90))
label.set_textcolor(lbl_info, vol_color(delta > 0, math.ceil((delta > 0 ? up_percent : dn_percent) - 50) / 50))
label.set_style(lbl_info, label.style_label_center)
label.set_text_font_family(lbl_info, font.family_default)
if barstate.isconfirmed
array.clear(prices)
array.clear(up_vol)
array.clear(dn_vol)
if mode == BID_VS_ASK
array.clear(labels_up)
array.clear(labels_dn)
array.clear(sorted_prices)
|
SZ PE Ratio | https://www.tradingview.com/script/LN8DmMt8-SZ-PE-Ratio/ | dsstudios12 | https://www.tradingview.com/u/dsstudios12/ | 21 | 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/
// © dsstudios12
//@version=5
indicator("SZ PE Ratio")
string str= (syminfo.prefix+":"+syminfo.ticker)
eps = request.financial(str, "EARNINGS_PER_SHARE", "TTM")
pe = close/eps
pe_avg = ta.sma(pe, 730)
plot(pe, color=color.blue)
plot(pe, color=color.green, trackprice = true, show_last = 1)
plot(pe_avg, color=color.purple)
|
Swing Levels and Liquidity - By Leviathan | https://www.tradingview.com/script/ljgpWxqE-Swing-Levels-and-Liquidity-By-Leviathan/ | LeviathanCapital | https://www.tradingview.com/u/LeviathanCapital/ | 3,808 | 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/
// © LeviathanCapital
//@version=5
indicator("Swing Points and Liquidity - By Leviathan", overlay=true, max_boxes_count=500, max_lines_count=500, max_labels_count = 500)
// Inputs
swingSizeR = input.int(10, 'Bars Right-Left', inline='brl')
swingSizeL = input.int(15, '-', inline='brl')
showBoxes = input.bool(true, 'Show Boxes ', inline='aa')
showSwingLines = input.bool(true, 'Show Lines', inline='aa')
showBubbles = input.bool(true, 'Show Labels ', inline='bb')
showVol = input.bool(false, 'Show Volume', inline='bb')
showOId = input.bool(false, 'Show OI Δ ', inline='cc')
extendtilfilled = input.bool(true, 'Extend Until Fill', inline='cc')
// Conditions
hidefilled = input.bool(false, 'Hide Filled', group='Conditions')
voltresh = input.int(0, 'Volume >', group='Conditions')
oitresh = input.int(0, 'OI Δ (abs.) >', group='Conditions')
pnoid = input.string('/', 'Only Swings With', options = ['Positive OI Delta', 'Negative OI Delta', '/'], group='Conditions')
// Appearance inputs
showhighs = input.bool(true, '', inline='sh', group='Appearance')
showlows = input.bool(true, '', inline='sl', group='Appearance')
sellcol = input.color(#aa2430, 'Lows (Line - Label - Box)', inline = 'sh', group='Appearance')
buycol = input.color(#66bb6a, 'Highs (Line - Label - Box)', inline='sl', group='Appearance')
sellcolB = input.color(#aa2430, '', inline='sh', group='Appearance')
buycolB = input.color(#66bb6a, '', inline = 'sl', group='Appearance')
sellboxCol = input.color(#80192231, '', inline = 'sh', group='Appearance')
buyboxCol = input.color(#66bb6a31, '', inline='sl', group='Appearance')
lineStyle = input.string('Dotted', 'Line Style + Width', ['Solid', 'Dashed', 'Dotted'], inline='l', group='Appearance')
lineWid = input.int(1, '', inline='l', group='Appearance')
boxWid = input.float(0.7, 'Box Width + Type ', step=0.1, inline='xx', group='Appearance')
boxStyle = input.string('TYPE 1', '', options=['TYPE 1', 'TYPE 2'], inline='xx', group='Appearance')
labelsize = input.string('Size: Tiny', 'Text Style ', options = ['Size: Normal','Size: Large', 'Size: Small', 'Size: Tiny', 'Size: Auto' ], inline='txt', group = 'Appearance' )
texthalign = input.string('Right','', options = ['Middle', 'Right', 'Left'], inline='txt', group = 'Appearance')
lookback = input.bool(false, '', inline='lb')
daysBack = input.float(150, 'Lookback (D) ',inline='lb')
// OI Data
binance = input.bool(true, 'Binance USDT.P', inline = 'src', group = 'Open Interest')
binance2 = input.bool(true, 'Binance USD.P', inline = 'src', group = 'Open Interest')
binance3 = input.bool(true, 'Binance BUSD.P', inline = 'src2', group = 'Open Interest')
bitmex = input.bool(true, 'BitMEX USD.P', inline = 'src2', group = 'Open Interest')
bitmex2 = input.bool(true, 'BitMEX USDT.P ', inline = 'src3', group = 'Open Interest')
kraken = input.bool(true, 'Kraken USD.P', inline = 'src3', group = 'Open Interest')
// Calculating inRange, used for lookback in days
MSPD = 24 * 60 * 60 * 1000
lastBarDate = timestamp(year(timenow), month(timenow), dayofmonth(timenow), hour(timenow), minute(timenow), second(timenow))
thisBarDate = timestamp(year, month, dayofmonth, hour, minute, second)
daysLeft = math.abs(math.floor((lastBarDate - thisBarDate) / MSPD))
inRange = lookback ? (daysLeft < daysBack) : true
//Pivot calculations
int prevHighIndex= na, int prevLowIndex= na, bool highActive= false, bool lowActive= false, bool h= false, bool l= false
pivHi = ta.pivothigh(high, swingSizeL, swingSizeR)
pivLo = ta.pivotlow(low, swingSizeL, swingSizeR)
if not na(pivHi)
h := true
prevHighIndex := bar_index - swingSizeR
if not na(pivLo)
l := true
prevLowIndex := bar_index - swingSizeR
// Getting OI data
mex = syminfo.basecurrency=='BTC' ? 'XBT' : string(syminfo.basecurrency)
oid1 = nz(request.security('BINANCE' + ":" + string(syminfo.basecurrency) + 'USDT.P_OI', timeframe.period, close-close[1], ignore_invalid_symbol = true), 0)
oid2 = nz(request.security('BINANCE' + ":" + string(syminfo.basecurrency) + 'USD.P_OI', timeframe.period, close-close[1], ignore_invalid_symbol = true), 0)
oid3 = nz(request.security('BINANCE' + ":" + string(syminfo.basecurrency) + 'BUSD.P_OI', timeframe.period, close-close[1], ignore_invalid_symbol = true), 0)
oid4 = nz(request.security('BITMEX' + ":" + mex + 'USD.P_OI', timeframe.period, close-close[1], ignore_invalid_symbol = true), 0)
oid5 = nz(request.security('BITMEX' + ":" + mex + 'USDT.P_OI', timeframe.period, close-close[1], ignore_invalid_symbol = true), 0)
oid6 = nz(request.security('KRAKEN' + ":" + string(syminfo.basecurrency) + 'USD.P_OI', timeframe.period, close-close[1], ignore_invalid_symbol = true), 0)
deltaOI = (binance ? nz(oid1,0) : 0) + (binance2 ? nz(oid2,0)/close : 0) + (binance3 ? nz(oid3,0) : 0) + (bitmex ? nz(oid4,0)/close : 0) + (bitmex2 ? nz(oid5,0)/close : 0) + (kraken ? nz(oid6,0)/close : 0)
//Volume, OI, box width
vol = volume[swingSizeR]
oitreshcond = oitresh > 0 ? math.abs(deltaOI[swingSizeR])>oitresh : true
voltreshcond = voltresh > 0 ? vol > voltresh : true
oicond = pnoid=='Positive OI Delta' ? deltaOI[swingSizeR]>0 : pnoid=='Negative OI Delta' ? deltaOI[swingSizeR]<0 : true
color CLEAR = color.rgb(0,0,0,100)
boxWid1 = 0.001 * boxWid
// Styles
boxStyle(x) =>
switch x
'TYPE 1' => h ? pivHi : l ? pivLo : na
'TYPE 2' => h ? pivHi * (1 - boxWid1) : l ? pivLo * (1 + boxWid1) : na
lineStyle(x) =>
switch x
'Solid' => line.style_solid
'Dashed' => line.style_dashed
'Dotted' => line.style_dotted
switchtextsize(textsize) =>
switch textsize
'Size: Normal' => size.normal
'Size: Small' => size.small
'Size: Tiny' => size.tiny
'Size: Auto' => size.auto
'Size: Large' => size.large
switchhalign(texthalign) =>
switch texthalign
'Middle' => text.align_center
'Right' => text.align_right
'Left' => text.align_left
//Swing level labels
var levelBoxes = array.new_box(), var levelLines = array.new_line()
if h and inRange and showhighs and oitreshcond and voltreshcond and oicond
hBox = box.new(prevHighIndex, pivHi * (1 + boxWid1), bar_index, boxStyle(boxStyle), border_color = na, bgcolor = showBoxes ? sellboxCol : CLEAR, text= (showVol ? str.tostring(vol, format.volume) : na) +' '+ (showOId ? str.tostring(deltaOI[swingSizeR], format.volume) : ''),text_halign=switchhalign(texthalign),text_valign=text.align_center,text_color=chart.fg_color, text_size=switchtextsize(labelsize))
hLine = line.new(prevHighIndex, pivHi, bar_index, pivHi, color = showSwingLines ? sellcol : CLEAR, style=lineStyle(lineStyle), width=lineWid)
array.push(levelBoxes, hBox)
array.push(levelLines, hLine)
if l and inRange and showhighs and oitreshcond and voltreshcond and oicond
lBox = box.new(prevLowIndex, pivLo * (1 - boxWid1), bar_index, boxStyle(boxStyle), border_color = na, bgcolor = showBoxes ? buyboxCol : CLEAR, text= (showVol ? str.tostring(vol, format.volume) : na) +' '+ (showOId ? str.tostring(deltaOI[swingSizeR], format.volume) : ''),text_halign=switchhalign(texthalign),text_valign=text.align_center,text_color=chart.fg_color, text_size=switchtextsize(labelsize))
lLine = line.new(prevLowIndex, pivLo, bar_index, pivLo, color = showSwingLines ? buycol : CLEAR, style=lineStyle(lineStyle), width=lineWid)
array.push(levelBoxes, lBox)
array.push(levelLines, lLine)
// Looping over the full array of lines and updating them, and deleting them if they have been touched
size = array.size(levelBoxes)
if size > 0
for i = 0 to size - 1
j = size - 1 - i
box = array.get(levelBoxes, j)
line = array.get(levelLines, j)
level = line.get_y2(line)
filled = (high >= level and low <= level)
if filled and extendtilfilled and not hidefilled
array.remove(levelLines, j)
array.remove(levelBoxes, j)
continue
box.set_right(box, bar_index+1)
line.set_x2(line, bar_index+1)
if filled and hidefilled
array.remove(levelLines, j)
array.remove(levelBoxes, j)
line.delete(line)
box.delete(box)
if not filled and not extendtilfilled
array.remove(levelLines, j)
array.remove(levelBoxes, j)
continue
box.set_right(box, bar_index[0]+4)
line.set_x2(line, bar_index[0]+4)
// Deleting the oldest lines if array is too big
if array.size(levelBoxes) >= 500
int i = 0
while array.size(levelBoxes) >= 500
box = array.get(levelBoxes, i)
line = array.get(levelLines, i)
box.delete(box)
line.delete(line)
array.remove(levelBoxes, i)
array.remove(levelLines, i)
i += 1
// Plotting circle labels
plotshape(showhighs and showBubbles and h and oitreshcond and voltreshcond and oicond ? high[swingSizeR] : na, style=shape.circle, location = location.absolute, offset = -swingSizeR, color=sellcolB, size = size.tiny)
plotshape(showlows and showBubbles and l and oitreshcond and voltreshcond and oicond ? low[swingSizeR] : na, style=shape.circle, location = location.absolute, offset = -swingSizeR, color=buycolB, size = size.tiny) |
Failed Breakdown Detection | https://www.tradingview.com/script/k9kxnH9R-Failed-Breakdown-Detection/ | xfuturesgod | https://www.tradingview.com/u/xfuturesgod/ | 100 | 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/
// © xfuturesgod
//@version=5
indicator("FBD Detection", overlay = true)
//user input
n_bars = input.int(defval=55, title="n bars", minval=1, step=1)
amp_thr = input.float(defval=0.05, title="amplitude threshold in % of past max amplitude", minval=0.0, maxval=1.0, step=0.01)
lengthGroupTitle = "LENGTH LEFT / RIGHT"
colorGroupTitle = "Text Color / Label Color"
leftLenL = input.int(title="Pivot Low", defval=10, minval=1, inline="Pivot Low", group=lengthGroupTitle)
rightLenL = input.int(title="/", defval=10, minval=1, inline="Pivot Low", group=lengthGroupTitle)
textColorL = input(title="Pivot Low", defval=color.black, inline="Pivot Low", group=colorGroupTitle)
labelColorL = input(title="", defval=color.white, inline="Pivot Low", group=colorGroupTitle)
lowerFBDThreshold = input.float(defval = 1.5, title = "FBD New Low Threshold - Lower", minval = 1.5)
upperFBDThreshold = input.float(defval = 10, title = "FBD New Low Threshold - Upper", minval = 1.5)
barLimit = input.int(defval = 10, title = "Number of Bars Under which the Previous Low Must Reclaim", minval = 2)
reclaimValue = input.float(defval = 8, title = "Price Reclaim Amount", minval = 3)
// declare pivot low variable and create array persistent array to store pivot lows
// draw pivot low labels
pivotLow = ta.pivotlow(leftLenL, rightLenL)
drawLabel(_offset, _pivot, _style, _color, _textColor) =>
if not na(_pivot)
label.new(bar_index[_offset], _pivot, str.tostring(_pivot, format.mintick), style=_style, color=_color, textcolor=_textColor)
drawLabel(rightLenL, pivotLow, label.style_label_up, labelColorL, textColorL)
plotchar(pivotLow,title = "PL", char = "P", location = location.abovebar,color = color.white)
var pivotLowArray = array.new_float(10,pivotLow)
pivotLowArraySize = array.size(pivotLowArray)
if pivotLow
array.push(pivotLowArray,pivotLow)
// plot first bar (18:00 EST for ES futures)
firstbar = session.isfirstbar
plotshape(firstbar,"opening bar", style = shape.flag, location = location.abovebar, color=color.blue )
EST730 = ta.barssince(firstbar) == 54
plotshape(EST730,"opening bar", style = shape.flag, location = location.abovebar, color=color.rgb(65, 209, 225) )
//amplitude
n_bars_hist = n_bars * 10
amp_up = (high - open) / open
amp_down = (open - low) / open
max_amp_up = ta.highest(amp_up, n_bars_hist)
max_amp_down = ta.highest(amp_down, n_bars_hist)
rel_amp_up = amp_up / max_amp_up
rel_amp_down = amp_down / max_amp_down
//nlnh value
//lowest/highest close/wick since x bars (relative to n_bars from 0 to 1)
lowest_wick_since = 1.0
highest_wick_since = 1.0
for i=1 to n_bars
if lowest_wick_since == 1.0 and low > low[i]
lowest_wick_since := (i - 1) / n_bars
if highest_wick_since == 1.0 and high < high[i]
highest_wick_since := (i - 1) / n_bars
if lowest_wick_since != 1.0 and highest_wick_since != 1.0
break
new_low = lowest_wick_since == 1.0 and rel_amp_down >= amp_thr
plotshape(new_low, style=shape.triangledown, location=location.belowbar, color=color.rgb(82, 183, 255))
// // alerts for new highs or lows made during all hours
alertcondition(new_low, "New Low Made", message = "New Low")
// variable for detecting new lows during "prime time" hours - 730AM and 400PM EST
rthNewLow = new_low and ta.barssince(EST730) > 0 and ta.barssince(EST730) < 33
// alerts when a new low occurs during or close to rth - regular US trading hours
alertcondition(rthNewLow, "New Low - RTH (7:30AM - 4:00PM EST", message = "New Low - RTH")
// determine if we have a valid set up failed breakdown and mark the entry candle
// valid set up = the new low must be within a certain threshold (1.5-10 points) vs the most recent pivot low, and pivot low must be "reclaimed"
// .... reclaim = 8 (default) points above the pivot low, within 10 bars of the occurence of the new low, and must be a green candle
// valid set up is a reclaim off the most recent pivot low. Once that pivot low is "reclaimed", it is added to an array to avoid duplicate signals
// ... from the same pivot low
latestPivotLow = array.get(pivotLowArray,pivotLowArraySize-1)
validLow = (latestPivotLow - low >= lowerFBDThreshold) and (latestPivotLow - low <= upperFBDThreshold)
underCut = new_low and validLow
var validSetupLevels = array.new_float(10,close)
validSetupLevelsArraySize = array.size(validSetupLevels)
lastLevelTraded = array.get(validSetupLevels,validSetupLevelsArraySize-1)
fbdEntry = (ta.barssince(underCut) < barLimit) and (high > (latestPivotLow + reclaimValue)) and (close > open) and (lastLevelTraded != latestPivotLow)
if fbdEntry
array.push(validSetupLevels,latestPivotLow)
plotchar(fbdEntry,title="fbdEntry",char = "X", location = location.abovebar, color = color.rgb(0, 255, 255))
alertcondition(fbdEntry, "Failed Breakdown Detected", message = "FBD Detected")
// variable for detecting new lows during "prime time" hours - 730AM and 400PM EST
rthFBD = fbdEntry and ta.barssince(EST730) > 0 and ta.barssince(EST730) < 33
// alerts when a new low occurs during or close to rth - regular US trading hours
alertcondition(rthFBD, "FBD - RTH (7:30AM - 4:00PM EST", message = "New Low - RTH")
|
Index Value Rainbow | https://www.tradingview.com/script/yKj4J8Zk-Index-Value-Rainbow/ | danny_peanuts | https://www.tradingview.com/u/danny_peanuts/ | 14 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © danny_peanuts
//
// Index value based on Base Money Supply
//
// Currently can be used to estimate the value of largest indices by market cap:
// - US Index - based on Net Liquidity (SPX, NDX, DJI, RUI, RUT, RUA, ES1!, NQ1!, YM1!, RTY1!)
// - EU Index - based on M1 Money Supply (N100, EU500, SXXP, SX5E, DAX, CAC40)
// - UK Index - based on M0 Money Supply (FTSE100, UK100)
// - JP Index - based on M0 Money Supply (NI225, NKY)
// - CN Index - based on M0 Money Supply (000001, 399001)
// - HK Index - based on M0 Money Supply (HSI)
// - SG Index - based on M0 Money Supply (STI)
// - CA Index - based on M0 Money Supply (TSX)
// - AU Index - based on M0 Money Supply (ASX200, AUS200)
// - ID Index - based on M0 Money Supply (COMPOSITE)
//
//@version=5
indicator("Index Value Rainbow", overlay = true)
// Net Liquidity = FHLB Balance Sheet + Fed Balance Sheet - Treasury General Account - Reverse Repo (more accurate than M0 data)
USM0 = request.security("(BOGZ1FL403069330Q + WALCL - WTREGEN - RRPONTSYD)", "D", close)
// M0 = 0.65 M1 (estimated value because there is no M0 data)
EUM0 = 0.65 * request.security("EUM1", "D", close)
GBM0 = request.security("GBM0", "D", close)
CNM0 = request.security("CNM0", "D", close)
JPM0 = request.security("JPM0", "D", close)
HKM0 = request.security("HKM0", "D", close)
SGM0 = request.security("SGM0", "D", close)
CAM0 = request.security("CAM0", "D", close)
AUM0 = request.security("AUM0", "D", close)
IDM0 = request.security("IDM0", "D", close)
V = 0 * USM0
if syminfo.ticker == "RUI" or syminfo.ticker == "RUT" or syminfo.ticker == "RUA" or syminfo.ticker == "RTY1!"
V := 1 * USM0 / 10000000000
if syminfo.ticker == "SPX" or syminfo.ticker == "ES1!"
V := 1 * USM0 / 10000000000
if syminfo.ticker == "NDX" or syminfo.ticker == "NQ1!"
V := 2.5 * USM0 / 10000000000
if syminfo.ticker == "DJI" or syminfo.ticker == "YM1!"
V := 10 * USM0 / 10000000000
if syminfo.ticker == "N100" or syminfo.ticker == "EU500"
V := 5 * EUM0 / 100000000000
if syminfo.ticker == "SXXP"
V := 2.5 * EUM0 / 100000000000
if syminfo.ticker == "SX5E" or syminfo.ticker == "CAC40"
V := 2.5 * EUM0 / 10000000000
if syminfo.ticker == "DAX"
V := 5 * EUM0 / 10000000000
if syminfo.ticker == "FTSE100" or syminfo.ticker == "UK100"
V := 2.5 * GBM0 / 100000000
if syminfo.ticker == "000001"
V := 1 * CNM0 / 10000000000
if syminfo.ticker == "399001"
V := 2.5 * CNM0 / 10000000000
if syminfo.ticker == "NKY" or syminfo.ticker == "NI225"
V := 7.5 * JPM0 / 100000000000
if syminfo.ticker == "HSI"
V := 2.5 * HKM0 / 100000000
if syminfo.ticker == "STI"
V := 2.5 * SGM0 / 100000000
if syminfo.ticker=="TSX"
V := 2.5 * CAM0 / 100000000
if syminfo.ticker=="ASX200" or syminfo.ticker == "AUS200"
V := 7.5 * AUM0 / 1000000000
if syminfo.ticker=="COMPOSITE"
V := 2.5 * IDM0 / 1000000000000
Vx10 = 10 * V
Vx9 = 9 * V
Vx8 = 8 * V
Vx7 = 7 * V
Vx6 = 6 * V
Vx5 = 5 * V
Vx4 = 4 * V
Vx3 = 3 * V
Vx2 = 2 * V
p1=plot(Vx10, "Vx10", color.rgb(133, 39, 176, 60))
p2=plot(Vx9, "Vx9", color.rgb(155, 39, 176, 60))
p3=plot(Vx8, "Vx8", color.rgb(223, 64, 251, 60))
p4=plot(Vx7, "Vx7", color.rgb(255, 82, 82, 60))
p5=plot(Vx6, "Vx6", color.rgb(255, 153, 0, 60))
p6=plot(Vx5, "Vx5", color.rgb(255, 235, 59, 60))
p7=plot(Vx4, "Vx4", color.rgb(0, 230, 119, 60))
p8=plot(Vx3, "Vx3", color.rgb(0, 187, 212, 60))
p9=plot(Vx2, "Vx2", color.rgb(33, 149, 243, 60))
p10=plot(V, "Vx0.8", color.rgb(120, 123, 134, 0), 2)
fill(p1, p2, top_value = Vx10, bottom_value = Vx9, top_color = color.rgb(133, 39, 176, 60), bottom_color = color.rgb(155, 39, 176, 60))
fill(p2, p3, top_value = Vx9, bottom_value = Vx8, top_color = color.rgb(155, 39, 176, 60), bottom_color = color.rgb(223, 64, 251, 80))
fill(p3, p4, top_value = Vx8, bottom_value = Vx7, top_color = color.rgb(223, 64, 251, 80), bottom_color = color.rgb(255, 82, 82, 80))
fill(p4, p5, top_value = Vx7, bottom_value = Vx6, top_color = color.rgb(255, 82, 82, 80), bottom_color = color.rgb(255, 153, 0, 80))
fill(p5, p6, top_value = Vx6, bottom_value = Vx5, top_color = color.rgb(255, 153, 0, 80), bottom_color = color.rgb(255, 235, 59, 80))
fill(p6, p7, top_value = Vx5, bottom_value = Vx4, top_color = color.rgb(255, 235, 59, 80), bottom_color = color.rgb(0, 230, 119, 80))
fill(p7, p8, top_value = Vx4, bottom_value = Vx3, top_color = color.rgb(0, 230, 119, 80), bottom_color = color.rgb(0, 187, 212, 80))
fill(p8, p9, top_value = Vx3, bottom_value = Vx2, top_color = color.rgb(0, 187, 212, 80), bottom_color = color.rgb(33, 149, 243, 80))
fill(p9, p10, top_value = Vx2, bottom_value = V, top_color = color.rgb(33, 149, 243, 80), bottom_color = color.rgb(120, 123, 134, 60))
|
OPG Indicator | https://www.tradingview.com/script/b2jPkUlR-OPG-Indicator/ | developdvb | https://www.tradingview.com/u/developdvb/ | 12 | 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/
// © developdvb
//@version=5
indicator("OPG Indicator", overlay = true)
gapSize = float(((open - close[1]) / close[1]) * 100)
plotColor = color.new(color.white, 0)
minGapSize = float(input(defval = -0.03000, title = "Min Gap Size"))
maxGapSize = float(input(defval = 0.03000, title = "Max Gap Size"))
float plotData = 0.0
if gapSize > maxGapSize
plotColor := color.new(color.red, 0)
plotData := -gapSize
else if gapSize < minGapSize
plotColor := color.new(color.green, 0)
plotData := -gapSize
plotarrow(series = plotData, colorup = color.new(color.green, 0), colordown = color.new(color.red, 0)) |
Strat Dashboard [TFO] | https://www.tradingview.com/script/tyHPA5Dj-Strat-Dashboard-TFO/ | tradeforopp | https://www.tradingview.com/u/tradeforopp/ | 646 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © tradeforopp
//@version=5
indicator("Strat Dashboard [TFO]", "Strat Dashboard [TFO]", true)
// -------------------- Inputs --------------------
var g_symbols = "Symbols"
last_x_candles = input.int(3, minval = 1, maxval = 10, title = "Show Last X Candles", group = g_symbols)
table_position = input.string('Top Right', "Table Position", options = ['Bottom Center', 'Bottom Left', 'Bottom Right', 'Middle Center', 'Middle Left', 'Middle Right', 'Top Center', 'Top Left', 'Top Right'], group = g_symbols)
enable_s1 = input.bool(true, "", inline = "S1", group = g_symbols)
s1 = input.symbol("SPY", "Symbol 1", inline = "S1", group = g_symbols)
enable_s2 = input.bool(true, "", inline = "S2", group = g_symbols)
s2 = input.symbol("TSLA", "Symbol 2", inline = "S2", group = g_symbols)
enable_s3 = input.bool(true, "", inline = "S3", group = g_symbols)
s3 = input.symbol("AAPL", "Symbol 3", inline = "S3", group = g_symbols)
enable_s4 = input.bool(true, "", inline = "S4", group = g_symbols)
s4 = input.symbol("QQQ", "Symbol 4", inline = "S4", group = g_symbols)
enable_s5 = input.bool(true, "", inline = "S5", group = g_symbols)
s5 = input.symbol("AMZN", "Symbol 5", inline = "S5", group = g_symbols)
enable_s6 = input.bool(true, "", inline = "S6", group = g_symbols)
s6 = input.symbol("NVDA", "Symbol 6", inline = "S6", group = g_symbols)
enable_s7 = input.bool(true, "", inline = "S7", group = g_symbols)
s7 = input.symbol("MSFT", "Symbol 7", inline = "S7", group = g_symbols)
enable_s8 = input.bool(true, "", inline = "S8", group = g_symbols)
s8 = input.symbol("META", "Symbol 8", inline = "S8", group = g_symbols)
enable_s9 = input.bool(true, "", inline = "S9", group = g_symbols)
s9 = input.symbol("AMD", "Symbol 9", inline = "S9", group = g_symbols)
enable_s10 = input.bool(true, "", inline = "S10", group = g_symbols)
s10 = input.symbol("GME", "Symbol 10", inline = "S10", group = g_symbols)
var g_table = "Table"
col_sss = input.bool(true, "SSS 50% Rule", group = g_table)
col_tfc = input.bool(true, "Timeframe Continuity", group = g_table)
col_last_rev = input.bool(true, "Last Strat Reversal", group = g_table)
col_ma1 = input.bool(true, "Moving Average 1", group = g_table)
col_ma2 = input.bool(true, "Moving Average 2", group = g_table)
col_vwap = input.bool(true, "VWAP", group = g_table)
var g_tfc = "Timeframe Continuity"
y1 = input.bool(true, "", inline = "1", group = g_tfc)
tf1 = input.timeframe("D", "Timeframe 1", inline = "1", group = g_tfc)
y2 = input.bool(true, "", inline = "2", group = g_tfc)
tf2 = input.timeframe("60", "Timeframe 2", inline = "2", group = g_tfc)
y3 = input.bool(true, "", inline = "3", group = g_tfc)
tf3 = input.timeframe("15", "Timeframe 3", inline = "3", group = g_tfc)
var g_rev = "Strat Reversals"
rev_22 = input.bool(true, "2-2", group = g_rev)
rev_122 = input.bool(true, "1-2-2", group = g_rev)
rev_212 = input.bool(true, "2-1-2", group = g_rev)
rev_312 = input.bool(true, "3-1-2", group = g_rev)
rev_322 = input.bool(true, "3-2-2", group = g_rev)
var g_ma = "Additional Information"
plot_vwap = input.bool(true, "Plot VWAP", inline = "PVWAP", group = g_ma)
vwap_color = input.color(color.blue, "", inline = "PVWAP", group = g_ma)
plot_fast_ma = input.bool(true, "Plot Fast EMA", inline = "PFAST", group = g_ma)
fast_color = input.color(color.green, "", inline = "PFAST", group = g_ma)
plot_slow_ma = input.bool(true, "Plot Slow EMA", inline = "PSLOW", group = g_ma)
slow_color = input.color(color.red, "", inline = "PSLOW", group = g_ma)
fast_ma = input.int(8, "Fast EMA Length", group = g_ma)
slow_ma = input.int(21, "Slow EMA Length", group = g_ma)
line_width = input.int(1, "Line Width", 1, group = g_ma)
var g_style = "Style"
up_color = input.color(#70ccbd, "In Force - Long", group = g_style)
dn_color = input.color(#f77c80, "In Force - Short", group = g_style)
table_text = input.color(color.black, "Text", group = g_style)
table_bg = input.color(color.white, "Table Background", group = g_style)
table_header = input.color(color.silver, "Table Header", group = g_style)
table_frame = input.color(color.gray, "Table Frame", group = g_style)
table_border = input.color(color.gray, "Table Border", inline = "TBG", group = g_style)
table_border_width = input.int(1, "", inline = "TBG", group = g_style)
var g_alert = "Alerts"
alert_confirmation = input.bool(false, "Wait for Confirmation", tooltip = "When true, will alert after the current bar closes and provides a valid strat reversal. Otherwise will alert immediately", group = g_alert)
// -------------------- Inputs --------------------
// -------------------- Initiate --------------------
table_position := switch table_position
"Bottom Center" => position.bottom_center
"Bottom Left" => position.bottom_left
"Bottom Right" => position.bottom_right
"Middle Center" => position.middle_center
"Middle Left" => position.middle_left
"Middle Right" => position.middle_right
"Top Center" => position.top_center
"Top Left" => position.top_left
"Top Right" => position.top_right
[s1_o, s1_h, s1_l, s1_c, s1_4] = request.security(s1, timeframe.period, [open, high, low, close, ohlc4], barmerge.gaps_off, barmerge.lookahead_on)
[s2_o, s2_h, s2_l, s2_c, s2_4] = request.security(s2, timeframe.period, [open, high, low, close, ohlc4], barmerge.gaps_off, barmerge.lookahead_on)
[s3_o, s3_h, s3_l, s3_c, s3_4] = request.security(s3, timeframe.period, [open, high, low, close, ohlc4], barmerge.gaps_off, barmerge.lookahead_on)
[s4_o, s4_h, s4_l, s4_c, s4_4] = request.security(s4, timeframe.period, [open, high, low, close, ohlc4], barmerge.gaps_off, barmerge.lookahead_on)
[s5_o, s5_h, s5_l, s5_c, s5_4] = request.security(s5, timeframe.period, [open, high, low, close, ohlc4], barmerge.gaps_off, barmerge.lookahead_on)
[s6_o, s6_h, s6_l, s6_c, s6_4] = request.security(s6, timeframe.period, [open, high, low, close, ohlc4], barmerge.gaps_off, barmerge.lookahead_on)
[s7_o, s7_h, s7_l, s7_c, s7_4] = request.security(s7, timeframe.period, [open, high, low, close, ohlc4], barmerge.gaps_off, barmerge.lookahead_on)
[s8_o, s8_h, s8_l, s8_c, s8_4] = request.security(s8, timeframe.period, [open, high, low, close, ohlc4], barmerge.gaps_off, barmerge.lookahead_on)
[s9_o, s9_h, s9_l, s9_c, s9_4] = request.security(s9, timeframe.period, [open, high, low, close, ohlc4], barmerge.gaps_off, barmerge.lookahead_on)
[s10_o, s10_h, s10_l, s10_c, s10_4] = request.security(s10, timeframe.period, [open, high, low, close, ohlc4], barmerge.gaps_off, barmerge.lookahead_on)
var s1_name = array.get(str.split(str.tostring(s1), ":"), 1) + " "
var s2_name = array.get(str.split(str.tostring(s2), ":"), 1) + " "
var s3_name = array.get(str.split(str.tostring(s3), ":"), 1) + " "
var s4_name = array.get(str.split(str.tostring(s4), ":"), 1) + " "
var s5_name = array.get(str.split(str.tostring(s5), ":"), 1) + " "
var s6_name = array.get(str.split(str.tostring(s6), ":"), 1) + " "
var s7_name = array.get(str.split(str.tostring(s7), ":"), 1) + " "
var s8_name = array.get(str.split(str.tostring(s8), ":"), 1) + " "
var s9_name = array.get(str.split(str.tostring(s9), ":"), 1) + " "
var s10_name = array.get(str.split(str.tostring(s10), ":"), 1) + " "
var table stats = table.new(table_position, 20, 20, bgcolor = table_bg, frame_color = table_frame, border_color = table_border, border_width = table_border_width)
// -------------------- Initiate --------------------
// -------------------- Functions --------------------
strat_candle(h, l, i) =>
result = ""
if h[i] > h[i + 1] and l[i] < l[i + 1]
result := "3"
else if h[i] <= h[i + 1] and l[i] < l[i + 1]
result := "2D"
else if h[i] > h[i + 1] and l[i] >= l[i + 1]
result := "2U"
else if h[i] <= h[i + 1] and l[i] >= l[i + 1]
result := "1"
result
compound_candles(c, h, l) =>
string result = ""
color current_color = na
for j = last_x_candles - 1 to 0
if j != last_x_candles - 1
result += " - "
result += strat_candle(h[j], l[j], j)
if c > h[1]
current_color := up_color
else if c < l[1]
current_color := dn_color
[result, current_color]
sss50(c, h, l) =>
string result = "NO"
color sss_color = na
midline = math.avg(h[1], l[1])
if h > h[1] and l > l[1] and c < midline
result := "YES"
sss_color := dn_color
else if h < h[1] and l < l[1] and c > midline
result := "YES"
sss_color := up_color
[result, sss_color]
strat_pattern(str, enable, ftfc_up, ftfc_dn) =>
c22 = false
c122 = false
c212 = false
c312 = false
c322 = false
if enable
split_arr = str.split(str, " - ")
size = array.size(split_arr)
if size >= 2
// 2 - 2
if rev_22 and ((array.get(split_arr, size - 2) == "2D" and array.get(split_arr, size - 1) == "2U") and ftfc_up or (array.get(split_arr, size - 2) == "2U" and array.get(split_arr, size - 1) == "2D") and ftfc_dn)
c22 := true
if size >= 3
// 1 - 2 - 2
if rev_122 and ((array.get(split_arr, size - 3) == "1" and array.get(split_arr, size - 2) == "2D" and array.get(split_arr, size - 1) == "2U") and ftfc_up or (array.get(split_arr, size - 3) == "1" and array.get(split_arr, size - 2) == "2U" and array.get(split_arr, size - 1) == "2D") and ftfc_dn)
c122 := true
// 2 - 1 - 2
if rev_212 and ((array.get(split_arr, size - 3) == "2D" and array.get(split_arr, size - 2) == "1" and array.get(split_arr, size - 1) == "2U") and ftfc_up or (array.get(split_arr, size - 3) == "2U" and array.get(split_arr, size - 2) == "1" and array.get(split_arr, size - 1) == "2D") and ftfc_dn)
c212 := true
// 3 - 1 - 2
if rev_312 and ((array.get(split_arr, size - 3) == "3" and array.get(split_arr, size - 2) == "1" and array.get(split_arr, size - 1) == "2U") and ftfc_up or (array.get(split_arr, size - 3) == "3" and array.get(split_arr, size - 2) == "1" and array.get(split_arr, size - 1) == "2D") and ftfc_dn)
c312 := true
// 3 - 2 - 2
if rev_322 and ((array.get(split_arr, size - 3) == "3" and array.get(split_arr, size - 2) == "2D" and array.get(split_arr, size - 1) == "2U") and ftfc_up or (array.get(split_arr, size - 3) == "3" and array.get(split_arr, size - 2) == "2U" and array.get(split_arr, size - 1) == "2D") and ftfc_dn)
c322 := true
[c22, c122, c212, c312, c322]
tfc(e1, e2, e3, o1, o2, o3, c) =>
ftfc_up = true
ftfc_dn = true
if e1
if c >= o1
ftfc_dn := false
else if c <= o1
ftfc_up := false
if e2
if c >= o2
ftfc_dn := false
else if c <= o2
ftfc_up := false
if e3
if c >= o3
ftfc_dn := false
else if c <= o3
ftfc_up := false
[ftfc_up, ftfc_dn]
get_ma(price) =>
fast_val = ta.ema(price, fast_ma)
slow_val = ta.ema(price, slow_ma)
ma1_color = price > fast_val ? up_color : dn_color
ma1_text = price > fast_val ? "Above" : "Below"
ma2_color = price > slow_val ? up_color : dn_color
ma2_text = price > slow_val ? "Above" : "Below"
[ma1_text, ma1_color, ma2_text, ma2_color]
get_vwap(c, o4) =>
value = ta.vwap(o4)
table_color = c > value ? up_color : dn_color
vwap_text = c > value ? "Above" : "Below"
[vwap_text, table_color]
get_all_info(c, h, l, o4) =>
[last_x, last_color] = compound_candles(c, h, l)
[sss50, sss50_color] = sss50(c, h, l)
[ma1_text, ma1_color, ma2_text, ma2_color] = get_ma(c)
[vwap_text, vwap_color] = get_vwap(c, o4)
[last_x, last_color, sss50, sss50_color, ma1_text, ma1_color, ma2_text, ma2_color, vwap_text, vwap_color]
// -------------------- Functions --------------------
// -------------------- TFC --------------------
// Timeframe 1
s1_1o = request.security(s1, tf1, open, barmerge.gaps_off, barmerge.lookahead_on)
s2_1o = request.security(s2, tf1, open, barmerge.gaps_off, barmerge.lookahead_on)
s3_1o = request.security(s3, tf1, open, barmerge.gaps_off, barmerge.lookahead_on)
s4_1o = request.security(s4, tf1, open, barmerge.gaps_off, barmerge.lookahead_on)
s5_1o = request.security(s5, tf1, open, barmerge.gaps_off, barmerge.lookahead_on)
s6_1o = request.security(s6, tf1, open, barmerge.gaps_off, barmerge.lookahead_on)
s7_1o = request.security(s7, tf1, open, barmerge.gaps_off, barmerge.lookahead_on)
s8_1o = request.security(s8, tf1, open, barmerge.gaps_off, barmerge.lookahead_on)
s9_1o = request.security(s9, tf1, open, barmerge.gaps_off, barmerge.lookahead_on)
s10_1o = request.security(s10, tf1, open, barmerge.gaps_off, barmerge.lookahead_on)
// Timeframe 2
s1_2o = request.security(s1, tf2, open, barmerge.gaps_off, barmerge.lookahead_on)
s2_2o = request.security(s2, tf2, open, barmerge.gaps_off, barmerge.lookahead_on)
s3_2o = request.security(s3, tf2, open, barmerge.gaps_off, barmerge.lookahead_on)
s4_2o = request.security(s4, tf2, open, barmerge.gaps_off, barmerge.lookahead_on)
s5_2o = request.security(s5, tf2, open, barmerge.gaps_off, barmerge.lookahead_on)
s6_2o = request.security(s6, tf2, open, barmerge.gaps_off, barmerge.lookahead_on)
s7_2o = request.security(s7, tf2, open, barmerge.gaps_off, barmerge.lookahead_on)
s8_2o = request.security(s8, tf2, open, barmerge.gaps_off, barmerge.lookahead_on)
s9_2o = request.security(s9, tf2, open, barmerge.gaps_off, barmerge.lookahead_on)
s10_2o = request.security(s10, tf2, open, barmerge.gaps_off, barmerge.lookahead_on)
// Timeframe 2
s1_3o = request.security(s1, tf3, open, barmerge.gaps_off, barmerge.lookahead_on)
s2_3o = request.security(s2, tf3, open, barmerge.gaps_off, barmerge.lookahead_on)
s3_3o = request.security(s3, tf3, open, barmerge.gaps_off, barmerge.lookahead_on)
s4_3o = request.security(s4, tf3, open, barmerge.gaps_off, barmerge.lookahead_on)
s5_3o = request.security(s5, tf3, open, barmerge.gaps_off, barmerge.lookahead_on)
s6_3o = request.security(s6, tf3, open, barmerge.gaps_off, barmerge.lookahead_on)
s7_3o = request.security(s7, tf3, open, barmerge.gaps_off, barmerge.lookahead_on)
s8_3o = request.security(s8, tf3, open, barmerge.gaps_off, barmerge.lookahead_on)
s9_3o = request.security(s9, tf3, open, barmerge.gaps_off, barmerge.lookahead_on)
s10_3o = request.security(s10, tf3, open, barmerge.gaps_off, barmerge.lookahead_on)
// Get TFC
[s1_ftfc_up, s1_ftfc_dn] = tfc(y1, y2, y3, s1_1o, s1_2o, s1_3o, s1_c)
[s2_ftfc_up, s2_ftfc_dn] = tfc(y1, y2, y3, s2_1o, s2_2o, s2_3o, s2_c)
[s3_ftfc_up, s3_ftfc_dn] = tfc(y1, y2, y3, s3_1o, s3_2o, s3_3o, s3_c)
[s4_ftfc_up, s4_ftfc_dn] = tfc(y1, y2, y3, s4_1o, s4_2o, s4_3o, s4_c)
[s5_ftfc_up, s5_ftfc_dn] = tfc(y1, y2, y3, s5_1o, s5_2o, s5_3o, s5_c)
[s6_ftfc_up, s6_ftfc_dn] = tfc(y1, y2, y3, s6_1o, s6_2o, s6_3o, s6_c)
[s7_ftfc_up, s7_ftfc_dn] = tfc(y1, y2, y3, s7_1o, s7_2o, s7_3o, s7_c)
[s8_ftfc_up, s8_ftfc_dn] = tfc(y1, y2, y3, s8_1o, s8_2o, s8_3o, s8_c)
[s9_ftfc_up, s9_ftfc_dn] = tfc(y1, y2, y3, s9_1o, s9_2o, s9_3o, s9_c)
[s10_ftfc_up, s10_ftfc_dn] = tfc(y1, y2, y3, s10_1o, s10_2o, s10_3o, s10_c)
// -------------------- TFC --------------------
// -------------------- Patterns --------------------
plot(plot_vwap ? ta.vwap(ohlc4) : na, "VWAP", vwap_color, linewidth = line_width)
plot(plot_fast_ma ? ta.ema(close, fast_ma) : na, "Fast EMA", fast_color, linewidth = line_width)
plot(plot_slow_ma ? ta.ema(close, slow_ma) : na, "Slow EMA", slow_color, linewidth = line_width)
[s1_last_x, s1_last_color, s1_sss50, s1_sss50_color, s1_ma1_text, s1_ma1_color, s1_ma2_text, s1_ma2_color, s1_vwap_text, s1_vwap_color] = get_all_info(s1_c, s1_h, s1_l, s1_4)
[s2_last_x, s2_last_color, s2_sss50, s2_sss50_color, s2_ma1_text, s2_ma1_color, s2_ma2_text, s2_ma2_color, s2_vwap_text, s2_vwap_color] = get_all_info(s2_c, s2_h, s2_l, s2_4)
[s3_last_x, s3_last_color, s3_sss50, s3_sss50_color, s3_ma1_text, s3_ma1_color, s3_ma2_text, s3_ma2_color, s3_vwap_text, s3_vwap_color] = get_all_info(s3_c, s3_h, s3_l, s3_4)
[s4_last_x, s4_last_color, s4_sss50, s4_sss50_color, s4_ma1_text, s4_ma1_color, s4_ma2_text, s4_ma2_color, s4_vwap_text, s4_vwap_color] = get_all_info(s4_c, s4_h, s4_l, s4_4)
[s5_last_x, s5_last_color, s5_sss50, s5_sss50_color, s5_ma1_text, s5_ma1_color, s5_ma2_text, s5_ma2_color, s5_vwap_text, s5_vwap_color] = get_all_info(s5_c, s5_h, s5_l, s5_4)
[s6_last_x, s6_last_color, s6_sss50, s6_sss50_color, s6_ma1_text, s6_ma1_color, s6_ma2_text, s6_ma2_color, s6_vwap_text, s6_vwap_color] = get_all_info(s6_c, s6_h, s6_l, s6_4)
[s7_last_x, s7_last_color, s7_sss50, s7_sss50_color, s7_ma1_text, s7_ma1_color, s7_ma2_text, s7_ma2_color, s7_vwap_text, s7_vwap_color] = get_all_info(s7_c, s7_h, s7_l, s7_4)
[s8_last_x, s8_last_color, s8_sss50, s8_sss50_color, s8_ma1_text, s8_ma1_color, s8_ma2_text, s8_ma2_color, s8_vwap_text, s8_vwap_color] = get_all_info(s8_c, s8_h, s8_l, s8_4)
[s9_last_x, s9_last_color, s9_sss50, s9_sss50_color, s9_ma1_text, s9_ma1_color, s9_ma2_text, s9_ma2_color, s9_vwap_text, s9_vwap_color] = get_all_info(s9_c, s9_h, s9_l, s9_4)
[s10_last_x, s10_last_color, s10_sss50, s10_sss50_color, s10_ma1_text, s10_ma1_color, s10_ma2_text, s10_ma2_color, s10_vwap_text, s10_vwap_color] = get_all_info(s10_c, s10_h, s10_l, s10_4)
[s1_22, s1_122, s1_212, s1_312, s1_322] = strat_pattern(s1_last_x, enable_s1, s1_ftfc_up, s1_ftfc_dn)
[s2_22, s2_122, s2_212, s2_312, s2_322] = strat_pattern(s2_last_x, enable_s2, s2_ftfc_up, s2_ftfc_dn)
[s3_22, s3_122, s3_212, s3_312, s3_322] = strat_pattern(s3_last_x, enable_s3, s3_ftfc_up, s3_ftfc_dn)
[s4_22, s4_122, s4_212, s4_312, s4_322] = strat_pattern(s4_last_x, enable_s4, s4_ftfc_up, s4_ftfc_dn)
[s5_22, s5_122, s5_212, s5_312, s5_322] = strat_pattern(s5_last_x, enable_s5, s5_ftfc_up, s5_ftfc_dn)
[s6_22, s6_122, s6_212, s6_312, s6_322] = strat_pattern(s6_last_x, enable_s6, s6_ftfc_up, s6_ftfc_dn)
[s7_22, s7_122, s7_212, s7_312, s7_322] = strat_pattern(s7_last_x, enable_s7, s7_ftfc_up, s7_ftfc_dn)
[s8_22, s8_122, s8_212, s8_312, s8_322] = strat_pattern(s8_last_x, enable_s8, s8_ftfc_up, s8_ftfc_dn)
[s9_22, s9_122, s9_212, s9_312, s9_322] = strat_pattern(s9_last_x, enable_s9, s9_ftfc_up, s9_ftfc_dn)
[s10_22, s10_122, s10_212, s10_312, s10_322] = strat_pattern(s10_last_x, enable_s10, s10_ftfc_up, s10_ftfc_dn)
any_22 = s1_22 or s2_22 or s3_22 or s4_22 or s5_22 or s6_22 or s7_22 or s8_22 or s9_22 or s10_22
any_122 = s1_122 or s2_122 or s3_122 or s4_122 or s5_122 or s6_122 or s7_122 or s8_122 or s9_122 or s10_122
any_212 = s1_212 or s2_212 or s3_212 or s4_212 or s5_212 or s6_212 or s7_212 or s8_212 or s9_212 or s10_212
any_312 = s1_312 or s2_312 or s3_312 or s4_312 or s5_312 or s6_312 or s7_312 or s8_312 or s9_312 or s10_312
any_322 = s1_322 or s2_322 or s3_322 or s4_322 or s5_322 or s6_322 or s7_322 or s8_322 or s9_322 or s10_322
any_s1 = s1_22 or s1_122 or s1_212 or s1_312 or s1_322
any_s2 = s2_22 or s2_122 or s2_212 or s2_312 or s2_322
any_s3 = s3_22 or s3_122 or s3_212 or s3_312 or s3_322
any_s4 = s4_22 or s4_122 or s4_212 or s4_312 or s4_322
any_s5 = s5_22 or s5_122 or s5_212 or s5_312 or s5_322
any_s6 = s6_22 or s6_122 or s6_212 or s6_312 or s6_322
any_s7 = s7_22 or s7_122 or s7_212 or s7_312 or s7_322
any_s8 = s8_22 or s8_122 or s8_212 or s8_312 or s8_322
any_s9 = s9_22 or s9_122 or s9_212 or s9_312 or s9_322
any_s10 = s10_22 or s10_122 or s10_212 or s10_312 or s10_322
any_s1_text = s1_122 ? "1 - 2 - 2" : s1_212 ? "2 - 1 - 2" : s1_312 ? "3 - 1 - 2" : s1_322 ? "3 - 2 - 2" : s1_22 ? "2 - 2" : "-"
any_s2_text = s2_122 ? "1 - 2 - 2" : s2_212 ? "2 - 1 - 2" : s2_312 ? "3 - 1 - 2" : s2_322 ? "3 - 2 - 2" : s2_22 ? "2 - 2" : "-"
any_s3_text = s3_122 ? "1 - 2 - 2" : s3_212 ? "2 - 1 - 2" : s3_312 ? "3 - 1 - 2" : s3_322 ? "3 - 2 - 2" : s3_22 ? "2 - 2" : "-"
any_s4_text = s4_122 ? "1 - 2 - 2" : s4_212 ? "2 - 1 - 2" : s4_312 ? "3 - 1 - 2" : s4_322 ? "3 - 2 - 2" : s4_22 ? "2 - 2" : "-"
any_s5_text = s5_122 ? "1 - 2 - 2" : s5_212 ? "2 - 1 - 2" : s5_312 ? "3 - 1 - 2" : s5_322 ? "3 - 2 - 2" : s5_22 ? "2 - 2" : "-"
any_s6_text = s6_122 ? "1 - 2 - 2" : s6_212 ? "2 - 1 - 2" : s6_312 ? "3 - 1 - 2" : s6_322 ? "3 - 2 - 2" : s6_22 ? "2 - 2" : "-"
any_s7_text = s7_122 ? "1 - 2 - 2" : s7_212 ? "2 - 1 - 2" : s7_312 ? "3 - 1 - 2" : s7_322 ? "3 - 2 - 2" : s7_22 ? "2 - 2" : "-"
any_s8_text = s8_122 ? "1 - 2 - 2" : s8_212 ? "2 - 1 - 2" : s8_312 ? "3 - 1 - 2" : s8_322 ? "3 - 2 - 2" : s8_22 ? "2 - 2" : "-"
any_s9_text = s9_122 ? "1 - 2 - 2" : s9_212 ? "2 - 1 - 2" : s9_312 ? "3 - 1 - 2" : s9_322 ? "3 - 2 - 2" : s9_22 ? "2 - 2" : "-"
any_s10_text = s10_122 ? "1 - 2 - 2" : s10_212 ? "2 - 1 - 2" : s10_312 ? "3 - 1 - 2" : s10_322 ? "3 - 2 - 2" : s10_22 ? "2 - 2" : "-"
// -------------------- Patterns --------------------
// -------------------- Populate Cells --------------------
table.cell(stats, 0, 0, "TF = " + str.tostring(timeframe.period), bgcolor = table_header)
table.cell(stats, 1, 0, "Last " + str.tostring(last_x_candles) + " Candles", bgcolor = table_header)
if col_sss
table.cell(stats, 2, 0, "SSS 50%", bgcolor = table_header)
if col_tfc
table.cell(stats, 3, 0, "TFC", bgcolor = table_header)
if col_last_rev
table.cell(stats, 4, 0, "Last", bgcolor = table_header)
if col_ma1
table.cell(stats, 5, 0, str.tostring(fast_ma) + " EMA", bgcolor = table_header)
if col_ma2
table.cell(stats, 6, 0, str.tostring(slow_ma) + " EMA", bgcolor = table_header)
if col_vwap
table.cell(stats, 7, 0, "VWAP", bgcolor = table_header)
// Symbol 1
if enable_s1
table.cell(stats, 0, 1, str.tostring(array.get(str.split(s1, ":"), 1)), text_color = table_text)
table.cell(stats, 1, 1, s1_last_x, bgcolor = s1_last_color, text_color = table_text)
if col_sss
table.cell(stats, 2, 1, s1_sss50, bgcolor = s1_sss50_color, text_color = table_text)
if col_tfc
table.cell(stats, 3, 1, s1_ftfc_up or s1_ftfc_dn ? "YES" : "NO", bgcolor = s1_ftfc_up ? up_color : s1_ftfc_dn ? dn_color : na, text_color = table_text)
if col_last_rev
table.cell(stats, 4, 1, any_s1[1] ? any_s1_text[1] : "-", bgcolor = any_s1[1] ? s1_last_color[1] : na, text_color = table_text)
if col_ma1
table.cell(stats, 5, 1, s1_ma1_text, bgcolor = s1_ma1_color, text_color = table_text)
if col_ma2
table.cell(stats, 6, 1, s1_ma2_text, bgcolor = s1_ma2_color, text_color = table_text)
if col_vwap
table.cell(stats, 7, 1, s1_vwap_text, bgcolor = s1_vwap_color, text_color = table_text)
// Symbol 2
if enable_s2
table.cell(stats, 0, 2, str.tostring(array.get(str.split(s2, ":"), 1)), text_color = table_text)
table.cell(stats, 1, 2, s2_last_x, bgcolor = s2_last_color, text_color = table_text)
if col_sss
table.cell(stats, 2, 2, s2_sss50, bgcolor = s2_sss50_color, text_color = table_text)
if col_tfc
table.cell(stats, 3, 2, s2_ftfc_up or s2_ftfc_dn ? "YES" : "NO", bgcolor = s2_ftfc_up ? up_color : s2_ftfc_dn ? dn_color : na, text_color = table_text)
if col_last_rev
table.cell(stats, 4, 2, any_s2[1] ? any_s2_text[1] : "-", bgcolor = any_s2[1] ? s2_last_color[1] : na, text_color = table_text)
if col_ma1
table.cell(stats, 5, 2, s2_ma1_text, bgcolor = s2_ma1_color, text_color = table_text)
if col_ma2
table.cell(stats, 6, 2, s2_ma2_text, bgcolor = s2_ma2_color, text_color = table_text)
if col_vwap
table.cell(stats, 7, 2, s2_vwap_text, bgcolor = s2_vwap_color, text_color = table_text)
// Symbol 3
if enable_s3
table.cell(stats, 0, 3, str.tostring(array.get(str.split(s3, ":"), 1)), text_color = table_text)
table.cell(stats, 1, 3, s3_last_x, bgcolor = s3_last_color, text_color = table_text)
if col_sss
table.cell(stats, 2, 3, s3_sss50, bgcolor = s3_sss50_color, text_color = table_text)
if col_tfc
table.cell(stats, 3, 3, s3_ftfc_up or s3_ftfc_dn ? "YES" : "NO", bgcolor = s3_ftfc_up ? up_color : s3_ftfc_dn ? dn_color : na, text_color = table_text)
if col_last_rev
table.cell(stats, 4, 3, any_s3[1] ? any_s3_text[1] : "-", bgcolor = any_s3[1] ? s3_last_color[1] : na, text_color = table_text)
if col_ma1
table.cell(stats, 5, 3, s3_ma1_text, bgcolor = s3_ma1_color, text_color = table_text)
if col_ma2
table.cell(stats, 6, 3, s3_ma2_text, bgcolor = s3_ma2_color, text_color = table_text)
if col_vwap
table.cell(stats, 7, 3, s3_vwap_text, bgcolor = s3_vwap_color, text_color = table_text)
// Symbol 4
if enable_s4
table.cell(stats, 0, 4, str.tostring(array.get(str.split(s4, ":"), 1)), text_color = table_text)
table.cell(stats, 1, 4, s4_last_x, bgcolor = s4_last_color, text_color = table_text)
if col_sss
table.cell(stats, 2, 4, s4_sss50, bgcolor = s4_sss50_color, text_color = table_text)
if col_tfc
table.cell(stats, 3, 4, s4_ftfc_up or s4_ftfc_dn ? "YES" : "NO", bgcolor = s4_ftfc_up ? up_color : s4_ftfc_dn ? dn_color : na, text_color = table_text)
if col_last_rev
table.cell(stats, 4, 4, any_s4[1] ? any_s4_text[1] : "-", bgcolor = any_s4[1] ? s4_last_color[1] : na, text_color = table_text)
if col_ma1
table.cell(stats, 5, 4, s4_ma1_text, bgcolor = s4_ma1_color, text_color = table_text)
if col_ma2
table.cell(stats, 6, 4, s4_ma2_text, bgcolor = s4_ma2_color, text_color = table_text)
if col_vwap
table.cell(stats, 7, 4, s4_vwap_text, bgcolor = s4_vwap_color, text_color = table_text)
// Symbol 5
if enable_s5
table.cell(stats, 0, 5, str.tostring(array.get(str.split(s5, ":"), 1)), text_color = table_text)
table.cell(stats, 1, 5, s5_last_x, bgcolor = s5_last_color, text_color = table_text)
if col_sss
table.cell(stats, 2, 5, s5_sss50, bgcolor = s5_sss50_color, text_color = table_text)
if col_tfc
table.cell(stats, 3, 5, s5_ftfc_up or s5_ftfc_dn ? "YES" : "NO", bgcolor = s5_ftfc_up ? up_color : s5_ftfc_dn ? dn_color : na, text_color = table_text)
if col_last_rev
table.cell(stats, 4, 5, any_s5[1] ? any_s5_text[1] : "-", bgcolor = any_s5[1] ? s5_last_color[1] : na, text_color = table_text)
if col_ma1
table.cell(stats, 5, 5, s5_ma1_text, bgcolor = s5_ma1_color, text_color = table_text)
if col_ma2
table.cell(stats, 6, 5, s5_ma2_text, bgcolor = s5_ma2_color, text_color = table_text)
if col_vwap
table.cell(stats, 7, 5, s5_vwap_text, bgcolor = s5_vwap_color, text_color = table_text)
// Symbol 6
if enable_s6
table.cell(stats, 0, 6, str.tostring(array.get(str.split(s6, ":"), 1)), text_color = table_text)
table.cell(stats, 1, 6, s6_last_x, bgcolor = s6_last_color, text_color = table_text)
if col_sss
table.cell(stats, 2, 6, s6_sss50, bgcolor = s6_sss50_color, text_color = table_text)
if col_tfc
table.cell(stats, 3, 6, s6_ftfc_up or s6_ftfc_dn ? "YES" : "NO", bgcolor = s6_ftfc_up ? up_color : s6_ftfc_dn ? dn_color : na, text_color = table_text)
if col_last_rev
table.cell(stats, 4, 6, any_s6[1] ? any_s6_text[1] : "-", bgcolor = any_s6[1] ? s6_last_color[1] : na, text_color = table_text)
if col_ma1
table.cell(stats, 5, 6, s6_ma1_text, bgcolor = s6_ma1_color, text_color = table_text)
if col_ma2
table.cell(stats, 6, 6, s6_ma2_text, bgcolor = s6_ma2_color, text_color = table_text)
if col_vwap
table.cell(stats, 7, 6, s6_vwap_text, bgcolor = s6_vwap_color, text_color = table_text)
// Symbol 7
if enable_s7
table.cell(stats, 0, 7, str.tostring(array.get(str.split(s7, ":"), 1)), text_color = table_text)
table.cell(stats, 1, 7, s7_last_x, bgcolor = s7_last_color, text_color = table_text)
if col_sss
table.cell(stats, 2, 7, s7_sss50, bgcolor = s7_sss50_color, text_color = table_text)
if col_tfc
table.cell(stats, 3, 7, s7_ftfc_up or s7_ftfc_dn ? "YES" : "NO", bgcolor = s7_ftfc_up ? up_color : s7_ftfc_dn ? dn_color : na, text_color = table_text)
if col_last_rev
table.cell(stats, 4, 7, any_s7[1] ? any_s7_text[1] : "-", bgcolor = any_s7[1] ? s7_last_color[1] : na, text_color = table_text)
if col_ma1
table.cell(stats, 5, 7, s7_ma1_text, bgcolor = s7_ma1_color, text_color = table_text)
if col_ma2
table.cell(stats, 6, 7, s7_ma2_text, bgcolor = s7_ma2_color, text_color = table_text)
if col_vwap
table.cell(stats, 7, 7, s7_vwap_text, bgcolor = s7_vwap_color, text_color = table_text)
// Symbol 8
if enable_s8
table.cell(stats, 0, 8, str.tostring(array.get(str.split(s8, ":"), 1)), text_color = table_text)
table.cell(stats, 1, 8, s8_last_x, bgcolor = s8_last_color, text_color = table_text)
if col_sss
table.cell(stats, 2, 8, s8_sss50, bgcolor = s8_sss50_color, text_color = table_text)
if col_tfc
table.cell(stats, 3, 8, s8_ftfc_up or s8_ftfc_dn ? "YES" : "NO", bgcolor = s8_ftfc_up ? up_color : s8_ftfc_dn ? dn_color : na, text_color = table_text)
if col_last_rev
table.cell(stats, 4, 8, any_s8[1] ? any_s8_text[1] : "-", bgcolor = any_s8[1] ? s8_last_color[1] : na, text_color = table_text)
if col_ma1
table.cell(stats, 5, 8, s8_ma1_text, bgcolor = s8_ma1_color, text_color = table_text)
if col_ma2
table.cell(stats, 6, 8, s8_ma2_text, bgcolor = s8_ma2_color, text_color = table_text)
if col_vwap
table.cell(stats, 7, 8, s8_vwap_text, bgcolor = s8_vwap_color, text_color = table_text)
// Symbol 9
if enable_s9
table.cell(stats, 0, 9, str.tostring(array.get(str.split(s9, ":"), 1)), text_color = table_text)
table.cell(stats, 1, 9, s9_last_x, bgcolor = s9_last_color, text_color = table_text)
if col_sss
table.cell(stats, 2, 9, s9_sss50, bgcolor = s9_sss50_color, text_color = table_text)
if col_tfc
table.cell(stats, 3, 9, s9_ftfc_up or s9_ftfc_dn ? "YES" : "NO", bgcolor = s9_ftfc_up ? up_color : s9_ftfc_dn ? dn_color : na, text_color = table_text)
if col_last_rev
table.cell(stats, 4, 9, any_s9[1] ? any_s9_text[1] : "-", bgcolor = any_s9[1] ? s9_last_color[1] : na, text_color = table_text)
if col_ma1
table.cell(stats, 5, 9, s9_ma1_text, bgcolor = s9_ma1_color, text_color = table_text)
if col_ma2
table.cell(stats, 6, 9, s9_ma2_text, bgcolor = s9_ma2_color, text_color = table_text)
if col_vwap
table.cell(stats, 7, 9, s9_vwap_text, bgcolor = s9_vwap_color, text_color = table_text)
// Symbol 10
if enable_s10
table.cell(stats, 0, 10, str.tostring(array.get(str.split(s10, ":"), 1)), text_color = table_text)
table.cell(stats, 1, 10, s10_last_x, bgcolor = s10_last_color, text_color = table_text)
if col_sss
table.cell(stats, 2, 10, s10_sss50, bgcolor = s10_sss50_color, text_color = table_text)
if col_tfc
table.cell(stats, 3, 10, s10_ftfc_up or s10_ftfc_dn ? "YES" : "NO", bgcolor = s10_ftfc_up ? up_color : s10_ftfc_dn ? dn_color : na, text_color = table_text)
if col_last_rev
table.cell(stats, 4, 10, any_s10[1] ? any_s10_text[1] : "-", bgcolor = any_s10[1] ? s10_last_color[1] : na, text_color = table_text)
if col_ma1
table.cell(stats, 5, 10, s10_ma1_text, bgcolor = s10_ma1_color, text_color = table_text)
if col_ma2
table.cell(stats, 6, 10, s10_ma2_text, bgcolor = s10_ma2_color, text_color = table_text)
if col_vwap
table.cell(stats, 7, 10, s10_vwap_text, bgcolor = s10_vwap_color, text_color = table_text)
// -------------------- Populate Cells --------------------
// -------------------- Alerts --------------------
alert_index = alert_confirmation ? 1 : 0
alertcondition(any_s1[alert_index], "Strat Reversal into TFC - Symbol 1")
alertcondition(any_s2[alert_index], "Strat Reversal into TFC - Symbol 2")
alertcondition(any_s3[alert_index], "Strat Reversal into TFC - Symbol 3")
alertcondition(any_s4[alert_index], "Strat Reversal into TFC - Symbol 4")
alertcondition(any_s5[alert_index], "Strat Reversal into TFC - Symbol 5")
alertcondition(any_s6[alert_index], "Strat Reversal into TFC - Symbol 6")
alertcondition(any_s7[alert_index], "Strat Reversal into TFC - Symbol 7")
alertcondition(any_s8[alert_index], "Strat Reversal into TFC - Symbol 8")
alertcondition(any_s9[alert_index], "Strat Reversal into TFC - Symbol 9")
alertcondition(any_s10[alert_index], "Strat Reversal into TFC - Symbol 10")
alertcondition(not na(s1_sss50_color[alert_index]) or not na(s2_sss50_color[alert_index]) or not na(s3_sss50_color[alert_index]) or not na(s4_sss50_color[alert_index]) or not na(s5_sss50_color[alert_index]) or not na(s6_sss50_color[alert_index]) or not na(s7_sss50_color[alert_index]) or not na(s8_sss50_color[alert_index]) or not na(s9_sss50_color[alert_index]) or not na(s10_sss50_color[alert_index]), "SSS 50% Rule - Any Symbol")
alertcondition(not na(s1_sss50_color[alert_index]), "SSS 50% Rule - Symbol 1")
alertcondition(not na(s2_sss50_color[alert_index]), "SSS 50% Rule - Symbol 2")
alertcondition(not na(s3_sss50_color[alert_index]), "SSS 50% Rule - Symbol 3")
alertcondition(not na(s4_sss50_color[alert_index]), "SSS 50% Rule - Symbol 4")
alertcondition(not na(s5_sss50_color[alert_index]), "SSS 50% Rule - Symbol 5")
alertcondition(not na(s6_sss50_color[alert_index]), "SSS 50% Rule - Symbol 6")
alertcondition(not na(s7_sss50_color[alert_index]), "SSS 50% Rule - Symbol 7")
alertcondition(not na(s8_sss50_color[alert_index]), "SSS 50% Rule - Symbol 8")
alertcondition(not na(s9_sss50_color[alert_index]), "SSS 50% Rule - Symbol 9")
alertcondition(not na(s10_sss50_color[alert_index]), "SSS 50% Rule - Symbol 10")
// -------------------- Alerts --------------------
|
Recursive Auto-Pitchfork [Trendoscope] | https://www.tradingview.com/script/hv8ghOJp-Recursive-Auto-Pitchfork-Trendoscope/ | Trendoscope | https://www.tradingview.com/u/Trendoscope/ | 839 | study | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © Trendoscope Pty Ltd
// ░▒
// ▒▒▒ ▒▒
// ▒▒▒▒▒ ▒▒
// ▒▒▒▒▒▒▒░ ▒ ▒▒
// ▒▒▒▒▒▒ ▒ ▒▒
// ▓▒▒▒ ▒ ▒▒▒▒▒▒▒▒▒▒▒
// ▒▒▒▒▒▒▒▒▒▒▒ ▒ ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
// ▒ ▒ ░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░▒▒▒▒▒▒▒▒
// ▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ▒▒
// ▒▒▒▒▒ ▒▒▒▒▒▒▒
// ▒▒▒▒▒▒▒▒▒
// ▒▒▒▒▒ ▒▒▒▒▒
// ░▒▒▒▒ ▒▒▒▒▓ ████████╗██████╗ ███████╗███╗ ██╗██████╗ ██████╗ ███████╗ ██████╗ ██████╗ ██████╗ ███████╗
// ▓▒▒▒▒ ▒▒▒▒ ╚══██╔══╝██╔══██╗██╔════╝████╗ ██║██╔══██╗██╔═══██╗██╔════╝██╔════╝██╔═══██╗██╔══██╗██╔════╝
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ██║ ██████╔╝█████╗ ██╔██╗ ██║██║ ██║██║ ██║███████╗██║ ██║ ██║██████╔╝█████╗
// ▒▒▒▒▒ ▒▒▒▒▒ ██║ ██╔══██╗██╔══╝ ██║╚██╗██║██║ ██║██║ ██║╚════██║██║ ██║ ██║██╔═══╝ ██╔══╝
// ▒▒▒▒▒ ▒▒▒▒▒ ██║ ██║ ██║███████╗██║ ╚████║██████╔╝╚██████╔╝███████║╚██████╗╚██████╔╝██║ ███████╗
// ▒▒ ▒
//@version=5
indicator("Recursive Auto-Pitchfork [Trendoscope]", "RAPF [Trendoscope]", overlay = true, max_lines_count=500)
import HeWhoMustNotBeNamed/DrawingTypes/2 as dr
import HeWhoMustNotBeNamed/DrawingMethods/2
import HeWhoMustNotBeNamed/ZigzagTypes/5 as zg
import HeWhoMustNotBeNamed/ZigzagMethods/6
import HeWhoMustNotBeNamed/PitchforkTypes/2 as p
import HeWhoMustNotBeNamed/PitchforkMethods/2
import HeWhoMustNotBeNamed/utils/1 as ut
// import HeWhoMustNotBeNamed/Logger/1 as l
// var logger = l.Logger.new(minimumLevel = 'DEBUG')
// logger.init()
theme = input.string('Dark', title='Theme', options=['Light', 'Dark'], group='Generic Settings',
tooltip='Chart theme settings. Line and label colors are generted based on the theme settings. If dark theme is selected, '+
'lighter colors are used and if light theme is selected, darker colors are used.')
zigzagLength = input.int(13, step=5, minval=3, title='Length', group='Zigzag', tooltip='Zigzag length for level 0 zigzag')
depth = input.int(50, "Depth", step=25, maxval=500, group='Zigzag', tooltip='Zigzag depth refers to max number of pivots to show on chart')
useRealTimeBars = input.bool(true, 'Use Real Time Bars', group='Zigzag', tooltip = 'If enabled real time bars are used for calculation. Otherwise, only confirmed bars are used')
typeTooltip = 'Handle Type' +
'\n\andrews - Pivot A' +
'\n\tschiff - X of Pivot A and y from median of Pivot A and B' +
'\n\tmschiff - X and Y are median of Pivot A and Pivot B' +
'\n\nNeck Type' +
'\n\tmedian - median of Pivot B and Pivot C' +
'\n\tinside - Pivot C'
pitchforkType = input.string("andrews", "Type", ["andrews", "schiff", "mschiff"], group="Pitchfork", inline="t")
neckType = input.string('median', '', ['median', 'inside'], group="Pitchfork", inline="t", tooltip=typeTooltip)
handle = pitchforkType=='andrews'?'regular': pitchforkType
inside = neckType == 'inside'
ratioFrom = input.float(0.25, 'Ratio', minval=0.0, maxval=0.5, group='Pitchfork', inline='r')
ratioTo = input.float(1, '', minval=0.5, maxval=1.618, group='Pitchfork', inline='r', tooltip='Range of ratio for which drawing pitchfork is allowed')
useConfirmedPivot = input.bool(true, 'Use Confirmed Pivots', group="Pitchfork", tooltip="If set to true, uses last confirmed pivot and ignores the current moving pivot")
includeRatio1 = input.bool(false, '', inline='r1', group='Forks')
ratio1 = input.float(0.236, '', inline='r1', group='Forks')
color1 = input.color(#f77c80, '', inline='r1', group='Forks')
includeRatio2 = input.bool(false, '', inline='r1', group='Forks')
ratio2 = input.float(0.382, '', inline='r1', group='Forks')
color2 = input.color(#ffb74d, '', inline='r1', group='Forks')
includeRatio3 = input.bool(true, '', inline='r2', group='Forks')
ratio3 = input.float(0.500, '', inline='r2', group='Forks')
color3 = input.color(#fff176, '', inline='r2', group='Forks')
includeRatio4 = input.bool(false, '', inline='r2', group='Forks')
ratio4 = input.float(0.618, '', inline='r2', group='Forks')
color4 = input.color(#81c784, '', inline='r2', group='Forks')
includeRatio5 = input.bool(false, '', inline='r3', group='Forks')
ratio5 = input.float(0.786, '', inline='r3', group='Forks')
color5 = input.color(#42bda8, '', inline='r3', group='Forks')
includeRatio6 = input.bool(false, '', inline='r3', group='Forks')
ratio6 = input.float(0.886, '', inline='r3', group='Forks')
color6 = input.color(#4dd0e1, '', inline='r3', group='Forks')
includeRatio7 = input.bool(true, '', inline='r4', group='Forks')
ratio7 = input.float(1.000, '', inline='r4', group='Forks')
color7 = input.color(#5b9cf6, '', inline='r4', group='Forks')
includeRatio8 = input.bool(false, '', inline='r4', group='Forks')
ratio8 = input.float(1.130, '', inline='r4', group='Forks')
color8 = input.color(#9575cd, '', inline='r4', group='Forks')
includeRatio9 = input.bool(false, '', inline='r5', group='Forks')
ratio9 = input.float(1.272, '', inline='r5', group='Forks')
color9 = input.color(#ba68c8, '', inline='r5', group='Forks')
includeRatio10 = input.bool(false, '', inline='r5', group='Forks')
ratio10 = input.float(1.382, '', inline='r5', group='Forks')
color10 = input.color(#f06292, '', inline='r5', group='Forks')
includeRatio11 = input.bool(false, '', inline='r6', group='Forks')
ratio11 = input.float(1.618, '', inline='r6', group='Forks')
color11 = input.color(#faa1a4, '', inline='r6', group='Forks')
includeRatio12 = input.bool(false, '', inline='r6', group='Forks')
ratio12 = input.float(2.000, '', inline='r6', group='Forks')
color12 = input.color(#4caf50, '', inline='r6', group='Forks')
extend = input.bool(true, "Extend", group="Display", tooltip = "Extend fork lines to right")
fill = input.bool(true, "Fill", group="Display", inline='f')
transparency = input.int(95, "Transparency", group="Display", inline='f', tooltip = "Fill Forkline with background color")
offset = useRealTimeBars? 0 : 1
indicators = matrix.new<float>()
indicatorNames = array.new<string>()
themeColors = ut.getColors(theme)
var zg.Zigzag zigzag = zg.Zigzag.new(zigzagLength, depth, offset)
zigzag.calculate(array.from(high, low), indicators, indicatorNames)
startIndex = useConfirmedPivot? 1:0
includes = array.from(includeRatio1, includeRatio2, includeRatio3, includeRatio4, includeRatio5, includeRatio6,
includeRatio7, includeRatio8, includeRatio9, includeRatio10, includeRatio11, includeRatio12)
ratios = array.from(ratio1, ratio2, ratio3, ratio4, ratio5, ratio6, ratio7, ratio8, ratio9, ratio10, ratio11, ratio12)
colors = array.from(color1, color2, color3, color4, color5, color6, color7, color8, color9, color10, color11, color12)
array<p.Fork> forks = array.new<p.Fork>()
for [i, include] in includes
if(include)
forks.push(p.Fork.new(ratios.get(i), colors.get(i), include))
p.PitchforkProperties properties = p.PitchforkProperties.new(forks, handle, inside)
p.PitchforkDrawingProperties dProperties = p.PitchforkDrawingProperties.new(extend, fill, transparency)
if(barstate.islast)
var array<p.Pitchfork> pitchforks = array.new<p.Pitchfork>()
pitchforks.clear()
mlzigzag = zigzag
while(mlzigzag.zigzagPivots.size() >= 3+startIndex)
lineColor = themeColors.pop()
themeColors.unshift(lineColor)
p3 = mlzigzag.zigzagPivots.get(startIndex)
p3Point = p3.point
p2Point = mlzigzag.zigzagPivots.get(startIndex+1).point
p1Point = mlzigzag.zigzagPivots.get(startIndex+2).point
if (p3.ratio >= ratioFrom and p3.ratio <= ratioTo and p3Point.bar - p1Point.bar <500)
dr.LineProperties lProperties = dr.LineProperties.new(color=lineColor)
p.Pitchfork pitchFork = p.Pitchfork.new(p1Point, p2Point, p3Point, properties, dProperties, lProperties)
drawing = pitchFork.createDrawing()
drawing.draw()
pitchforks.push(pitchFork)
mlzigzag := mlzigzag.nextlevel() |
Recession Warning Traffic Light | https://www.tradingview.com/script/lxXLkR1w-Recession-Warning-Traffic-Light/ | BarefootJoey | https://www.tradingview.com/u/BarefootJoey/ | 678 | 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/
// © BarefootJoey
// ██████████████████████████████████████████████████████████████████████
// █▄─▄─▀██▀▄─██▄─▄▄▀█▄─▄▄─█▄─▄▄─█─▄▄─█─▄▄─█─▄─▄─███▄─▄█─▄▄─█▄─▄▄─█▄─█─▄█
// ██─▄─▀██─▀─███─▄─▄██─▄█▀██─▄███─██─█─██─███─███─▄█─██─██─██─▄█▀██▄─▄██
// █▄▄▄▄██▄▄█▄▄█▄▄█▄▄█▄▄▄▄▄█▄▄▄███▄▄▄▄█▄▄▄▄██▄▄▄██▄▄▄███▄▄▄▄█▄▄▄▄▄██▄▄▄██
//@version=5
indicator('Recession Warning Traffic Light')
// Groups
grfr = "Federal Reserve"
gryc = "Yield Curve"
grm2 = "Money Supply"
grsp = "Stock Market"
grpm = "Precious Metals"
grle = "Leading Economic Indicator"
grw = "Recession Warning"
// BarefootJoey's indicator('Moving Average Growth Rate', precision=4) // (Daily Updates)
sp500 = request.security('SPX', "W", close)
psma_length = 16 //input(16, title='Price SMA Length', group=grsp)
sustainable = input.float(2, title='Sustainable Growth Rate', group=grsp)
current_ma = ta.sma(sp500, psma_length)
previous_ma = current_ma[1]
delta = current_ma - previous_ma
growthrate = delta / previous_ma
growthrate_percentage = growthrate * 100
bau2 = growthrate_percentage < sustainable and growthrate_percentage >= 0
heating_up2 = growthrate_percentage >= sustainable
warning2 = growthrate_percentage < 0
plot_color2 = bau2 ? color.green : heating_up2 ? color.orange : warning2 ? color.red : color.gray
// US 3m/10y Inversion (Daily Updates)
us3m = request.security('US03MY', "D", close)
us10y = request.security('US10Y', "D", close)
us10y3m = (us10y - us3m) * 100
us10y3m_col = us10y3m>0?color.green:us10y3m<0?color.red:na
us10y3m_col2 = us10y3m>0?color.green:us10y3m<0?color.red:color.gray
// M2 Money Supply (Monthly Updates)
m2sl = request.security('M2SL', "D", close)
// M2 Trend State
var m2state = 0
if m2sl>m2sl[1]
m2state := 1
m2state
if m2sl<m2sl[1]
m2state := -1
m2state
m2state := m2state
m2sl_col = m2state==1?color.green:m2state==-1?color.red:na
// Federal Reserve GDP/Growth
sustainable2 = input.float(2.5, "Sustainable Growth", minval=0, group=grfr)
i_input = input.symbol("GDPC1", title="Growth Ticker", group=grfr) //, tooltip="You may get errors if your chart is set to a different timeframe/ticker than 1d CPILFESL")
tickeri = request.security(i_input, "D", close)
// GDP Trend State
var gdpstate = 0
if tickeri>tickeri[1]
gdpstate := 1
gdpstate
if tickeri<tickeri[1]
gdpstate := -1
gdpstate
gdpstate := gdpstate
gdp_col = gdpstate==1?color.green:gdpstate==-1?color.red:na
// BarefootJoey's indicator('Precious Metal Ratios')
f_security(_symbol, _res, _src) =>
request.security(_symbol, _res, _src)
goldpr = f_security('TVC:GOLD', "W", close) // D, W, or M depending on noise level desired
rhodpr = f_security('LSE:XRH0', "W", close) // D, W, or M depending on noise level desired
pmfinal = rhodpr / goldpr
pmfinaltxt_col = pmfinal < pmfinal[1] ? color.green : pmfinal > pmfinal[1] ? color.red : color.gray
// PM Trend State
var pmstate = 0
if pmfinal < pmfinal[1]
pmstate := 1
pmstate
if pmfinal > pmfinal[1]
pmstate := -1
pmstate
pmstate := pmstate
pm_col = pmstate==1?color.green:pmstate==-1?color.red:na
// Leading Ecnomic Data of Choice
i_input2 = input.symbol("UNRATE", title="Leading Economic Indicator", group=grle, tooltip="Baskets of leading economic indicators, as collections, reflect overall growth or contraction of economic activity. These indicators include measures of level and growth in productivity, employment, housing, consumer confidence, industrial purchasing confidence, and much more.")
tickeri2 = request.security(i_input2, "D", close)
// LE Trend State
var lestate = 0
if tickeri2<tickeri2[1]
lestate := 1
lestate
if tickeri2>tickeri2[1]
lestate := -1
lestate
lestate := lestate
le_col = lestate==1?color.green:lestate==-1?color.red:na
// All bullish/bearish
bgbull_col = gdpstate==1 and us10y3m>0 and m2state==1 and (bau2 or heating_up2) and pmstate==1 and lestate==1 ? color.new(color.green,80) : na
bgbear_col = gdpstate==-1 and us10y3m<0 and m2state==-1 and warning2 and pmstate==-1 and lestate==-1 ? color.new(color.red,80) : na
combined_col = gdpstate==1 and us10y3m>0 and m2state==1 and (bau2 or heating_up2) and pmstate==1 and lestate==1 ? color.new(color.green,0) : gdpstate==-1 and us10y3m<0 and m2state==-1 and warning2 and pmstate==-1 and lestate==-1 ? color.new(color.red,0) : color.gray
// Recession probability
rec_prob = (lestate==1?0:lestate==-1?20:10) + (pmstate==1?0:pmstate==-1?20:10) + (gdpstate==1?0:gdpstate==-1?20:10) + (m2state==1?0:m2state==-1?20:10) + (us10y3m>0?0:us10y3m<0?20:10) + (bau2?0:heating_up2?10:warning2?20:0)
plot(rec_prob, color=combined_col)
var label rp = na
if barstate.islast
rp := label.new(bar_index, y=rec_prob, text=str.tostring(rec_prob)+"%", size=size.small, style=label.style_label_left, color=color.new(color.white,100), textcolor=color.new(combined_col,0), tooltip="Recession Probability")
label.delete(rp[1])
// Recession Warnings
w_thresh = input.int(50, "Warning Threshold", minval=0, maxval=100, group=grw)
warning = rec_prob>w_thresh?color.orange:color.new(color.orange,100)
//warning_bg = rec_prob>w_thresh?color.orange:na
plot(-10, "Recession Warning", color=warning, linewidth=4)
var label w = na
if barstate.islast
w := label.new(bar_index, y=-10, text="Warning!", size=size.small, style=label.style_label_left, color=color.new(color.white,100), textcolor=warning, tooltip="Recession Probability above " + str.tostring(w_thresh) + "%")
label.delete(w[1])
// Actual Recessions
rec_src = request.quandl("FRED/USRECD") // Recession data from Federal Reserve
rec_col = rec_src == 1 ? color.new(color.red,0) : color.new(color.red,100) // if value is 1, call True (means there is a recession)
plot(-5, "Actual Recession", color=rec_col, linewidth=4)
var label ar = na
if barstate.islast
ar := label.new(bar_index, y=-5, text="Recession!", size=size.small, style=label.style_label_left, color=color.new(color.white,100), textcolor=rec_col, tooltip="S&P 500 Growth Rate (4 Month)")
label.delete(ar[1])
// Traffic Light Plots
// Stock Market Growth
plot(-35, "Stock Market", color=plot_color2, linewidth=4)
var label gr = na
if barstate.islast
gr := label.new(bar_index, y=-35, text="Stock Market", size=size.small, style=label.style_label_left, color=color.new(color.white,100), textcolor=color.new(plot_color2,0), tooltip="S&P 500 Growth Rate (4 Month)")
label.delete(gr[1])
// Treasury Yield Curve Inversion
plot(-30, "Yield Curve", color=us10y3m_col, linewidth=4)
var label inv = na
if barstate.islast
inv := label.new(bar_index, y=-30, text="Yield Curve", size=size.small, style=label.style_label_left, color=color.new(color.white,100), textcolor=color.new(us10y3m_col2,0), tooltip="US 10y/3m Yield Curve Inversion")
label.delete(inv[1])
// M2 Money Supply
plot(-20, "Money Supply", color=m2sl_col, linewidth=4)
var label m2 = na
if barstate.islast
m2 := label.new(bar_index, y=-20, text="Money Supply", size=size.small, style=label.style_label_left, color=color.new(color.white,100), textcolor=color.new(m2sl_col,0), tooltip="M2 Money Supply")
label.delete(m2[1])
// Federal Reserve, Growth/GDP
plot(-25, "Federal Reserve", color=gdp_col, linewidth=4)
var label fr = na
if barstate.islast
fr := label.new(bar_index, y=-25, text="Federal Reserve", size=size.small, style=label.style_label_left, color=color.new(color.white,100), textcolor=color.new(gdp_col,0), tooltip="Economic Growth (GDP)")
label.delete(fr[1])
// Precious Metals
plot(-40, "Precious Metals", color=pm_col, linewidth=4)
var label pm = na
if barstate.islast
pm := label.new(bar_index, y=-40, text="Precious Metals", size=size.small, style=label.style_label_left, color=color.new(color.white,100), textcolor=color.new(pmfinaltxt_col,0), tooltip="Rhodium:Gold Ratio")
label.delete(pm[1])
// Leading Economic Indicator
plot(-15, "Lead Econ Indicator", color=le_col, linewidth=4)
var label le = na
if barstate.islast
le := label.new(bar_index, y=-15, text="Lead Indicator", size=size.small, style=label.style_label_left, color=color.new(color.white,100), textcolor=color.new(le_col,0), tooltip=syminfo.ticker(i_input2))
label.delete(le[1])
// EoS made w/ ❤ by @BarefootJoey ✌💗📈 |
Haydens RSI Trend Trader | https://www.tradingview.com/script/yriGQnZs-Haydens-RSI-Trend-Trader/ | BarefootJoey | https://www.tradingview.com/u/BarefootJoey/ | 1,241 | 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/
// © BarefootJoey
// ██████████████████████████████████████████████████████████████████████
// █▄─▄─▀██▀▄─██▄─▄▄▀█▄─▄▄─█▄─▄▄─█─▄▄─█─▄▄─█─▄─▄─███▄─▄█─▄▄─█▄─▄▄─█▄─█─▄█
// ██─▄─▀██─▀─███─▄─▄██─▄█▀██─▄███─██─█─██─███─███─▄█─██─██─██─▄█▀██▄─▄██
// █▄▄▄▄██▄▄█▄▄█▄▄█▄▄█▄▄▄▄▄█▄▄▄███▄▄▄▄█▄▄▄▄██▄▄▄██▄▄▄███▄▄▄▄█▄▄▄▄▄██▄▄▄██
//@version=5
indicator("Haydens RSI Trend Trader", overlay = true)
// ---------------------------- Theme --------------------------------------- //
// Colors
red = color.red
green = color.green
brightred = #ff1100
brightgreen = #00ff0a
cautioncol = color.yellow
gray= color.gray
aqua = color.aqua
orange= color.orange
darkgreen = #1b5e20
darkred = #801922
// Groups
grma = "📈 Moving Averages 📈"
grhts = "Triple Trend State"
grt = "🎯 Targets 🎯"
grll = "🩸 Leverage Liquidations 🩸"
gla= "🔔 Alerts 🔔"
// Constants
dataType = "Custom"
instructions = "Off"
smaS = "Off"
constant = 1>0
rsi=ta.rsi(close,14)
// ------------------------- Trend State ------------------------------------ //
// Code Author: © Koalafied_3
showtrend = input(true, title='Show Hayden triple trend state H-line fill?',group=grhts,
tooltip ="Check this box if you want to see the Bull, Bear, or Chop trend state background according to Hayden.\n(Page 56) 10 Lies That Traders Believe = The RSI is unable to indicate trend direction, because it's only a momentum indicator.")
showbc = input(true, title='Show Hayden triple trend state Chart Bar Color?',group=grhts)
ts1 = input.float(defval=67, title="Precise Bullish RSI Crossover 66 to 68", minval=66, maxval=68, step=0.001, group=grhts, tooltip="End of chop. Popular: 66, 66.666, or 67")
ts2 = input.float(defval=33, title="Precise Bearish RSI Crossunder 32 to 34", minval=32, maxval=34, step=0.001, group=grhts, tooltip="End of chop. Popular: 34, 33.333, or 33")
ts1a = input.float(defval=61, title="Precise Bullish RSI Crossover 60 to 62", minval=60, maxval=62, step=0.001, group=grhts, tooltip="End of bearish trend. Popular: 61, 60.618, 60.5, or 60")
ts2a = input.float(defval=39, title="Precise Bearish RSI Crossunder 38 to 40", minval=38, maxval=40, step=0.001, group=grhts, tooltip="End of bullish trend. Popular: 39, 39.5, 39.618, or 40")
// Trend State
var state = 0
if ta.crossover(rsi, ts1)
state := 1
state
if ta.crossunder(rsi, ts2)
state := 2
state
state := state
//-----------------3 State RSI Gradient Bar Color on Chart--------------------//
cbullu = input(brightgreen, "Chart BarColor: Bull Run", group=grhts)
cbulld = input(darkgreen, "Chart BarColor: Bull Pullback", group=grhts)
cbearu = input(brightred, "Chart BarColor: Bear Run", group=grhts)
cbeard = input(darkred, "Chart BarColor: Bear Pullback", group=grhts)
cbearc = input(brightgreen, "Chart BarColor: Bull Chop", group=grhts)
cbullc = input(brightred, "Chart BarColor: Bear Chop", group=grhts)
barcolor(state==1 and rsi>50?cbullu: state==1 and rsi<50?cbulld: state==2 and rsi<50 ?cbearu: state==2 and rsi>50 ?cbeard:color.new(color.from_gradient(rsi, ts2, ts1, cbearu, cbullu),0),title="Chart Bar Color", display = showbc ? display.all : display.none, editable=false)
// RSI 50 Line
// @ LazyBear
obLevelM = 50
src = close
length = 14
ep = 2 * length - 1
auc = ta.ema(math.max(src - src[1], 0), ep)
adc = ta.ema(math.max(src[1] - src, 0), ep)
x7 = (length - 1) * (adc * obLevelM / (100 - obLevelM) - auc)
ub4 = x7 >= 0 ? src + x7 : src + x7 * (100 - obLevelM) / obLevelM
plot(ub4, title='Midline', color=color.new(ub4>ub4[1]?color.green:ub4<ub4[1]?color.red:color.gray, 25), linewidth=1)
// ------------------------------- Alerts ----------------------------------- //
alert_freq = input.string(alert.freq_once_per_bar_close, "Alert Frequency", options=[alert.freq_once_per_bar_close, alert.freq_once_per_bar, alert.freq_all], group = gla)
bar_update_alerts = input.bool(false, "Trade updates each bar?", tooltip="Check this box to receive an alert with the current trade status every time the bar closes.")
// ---------------------------- Trade Setup --------------------------------- //
// Inspired by @ KioseffTrading
lot_size = input.float(1, 'Lot Size', minval=0, group=grt, step=0.001)
dcaorstop = input.string("Stop", "DCA 3 or Stop", options=["DCA 3", "Stop"], group=grt)
// Number of Decimals for Labels
pricedecimals= input.int(defval=2, title='Number of Price Decimals', minval=0, maxval=10, group=grt)
truncateprice(number, pricedecimals) =>
factor = math.pow(10, pricedecimals)
int(number * factor) / factor
// Define a bull/bear cross
bullcross= state==1 and state[1]==2
bearcross= state==2 and state[1]==1
// Detect what was last signal (long or short)
long_short = 0
long_last = bullcross and (nz(long_short[1]) == 0 or nz(long_short[1]) == -1)
short_last = bearcross and (nz(long_short[1]) == 0 or nz(long_short[1]) == 1)
long_short := long_last ? 1 : short_last ? -1 : long_short[1]
// Remove first bar for SL/TP (you can't enter a trade at bar close and THEN hit your SL on that same bar)
longBar1 = ta.barssince(long_last)
longBar2 = longBar1 >= 1 ? true : false
shortBar1 = ta.barssince(short_last)
shortBar2 = shortBar1 >= 1 ? true : false
// Wen entry, sir?
bullentry = ta.valuewhen(bullcross, close, 0)
bearentry = ta.valuewhen(bearcross, close, 0)
entin= state==1 and long_short==1?bullentry:state==2 and long_short==-1?bearentry:na
entout=plot(entin, 'Entry', color=color.new(color.gray, 0), style=plot.style_circles, editable=false)
// Targets
// ATR TP & SL
srcATR = input(title='ATR Source', defval=close, group=grt)
atrPeriod = input.int(title='ATR Period', defval=233, minval=1, group=grt)
per = atrPeriod
atrMultiplier = input.float(title='ATR Multiplier', defval=10, group=grt)
atr = ta.atr(atrPeriod)
ATRupper=srcATR + atr * atrMultiplier
ATRlower=srcATR - atr * atrMultiplier
ATRupper2=srcATR + atr * (atrMultiplier*0.854)
ATRlower2=srcATR - atr * (atrMultiplier*0.854)
ATRupper3=srcATR + atr * (atrMultiplier*0.763)
ATRlower3=srcATR - atr * (atrMultiplier*0.763)
ATRupper4=srcATR + atr * (atrMultiplier*0.618)
ATRlower4=srcATR - atr * (atrMultiplier*0.618)
ATRupper5=srcATR + atr * (atrMultiplier*0.5)
ATRlower5=srcATR - atr * (atrMultiplier*0.5)
ATRupper6=srcATR + atr * (atrMultiplier*0.382)
ATRlower6=srcATR - atr * (atrMultiplier*0.382)
ATRupper7=srcATR + atr * (atrMultiplier*0.236)
ATRlower7=srcATR - atr * (atrMultiplier*0.236)
ATRupper8=srcATR + atr * (atrMultiplier*0.146)
ATRlower8=srcATR - atr * (atrMultiplier*0.146)
bearse=srcATR + atr * (atrMultiplier*0.146)
bullse=srcATR - atr * (atrMultiplier*0.146)
bearse2=srcATR + atr * (atrMultiplier*0.236)
bullse2=srcATR - atr * (atrMultiplier*0.236)
bearse3=srcATR + atr * (atrMultiplier*0.382)
bullse3=srcATR - atr * (atrMultiplier*0.382)
ATRbulltp1=ta.valuewhen(bullcross,ATRupper,0)
ATRbeartp1=ta.valuewhen(bearcross,ATRlower,0)
ATRbulltp2=ta.valuewhen(bullcross,ATRupper2,0)
ATRbeartp2=ta.valuewhen(bearcross,ATRlower2,0)
ATRbulltp3=ta.valuewhen(bullcross,ATRupper3,0)
ATRbeartp3=ta.valuewhen(bearcross,ATRlower3,0)
ATRbulltp4=ta.valuewhen(bullcross,ATRupper4,0)
ATRbeartp4=ta.valuewhen(bearcross,ATRlower4,0)
ATRbulltp5=ta.valuewhen(bullcross,ATRupper5,0)
ATRbeartp5=ta.valuewhen(bearcross,ATRlower5,0)
ATRbulltp6=ta.valuewhen(bullcross,ATRupper6,0)
ATRbeartp6=ta.valuewhen(bearcross,ATRlower6,0)
ATRbulltp7=ta.valuewhen(bullcross,ATRupper7,0)
ATRbeartp7=ta.valuewhen(bearcross,ATRlower7,0)
ATRbulltp8=ta.valuewhen(bullcross,ATRupper8,0)
ATRbeartp8=ta.valuewhen(bearcross,ATRlower8,0)
vwbearse=ta.valuewhen(bearcross,bearse,0)
vwbullse=ta.valuewhen(bullcross,bullse,0)
vwbearse2=ta.valuewhen(bearcross,bearse2,0)
vwbullse2=ta.valuewhen(bullcross,bullse2,0)
vwbearse3=ta.valuewhen(bearcross,bearse3,0)
vwbullse3=ta.valuewhen(bullcross,bullse3,0)
bgrad = 80
tgrad = 95
exin = state==1 and long_short==1?ATRbulltp1:state==2 and long_short==-1?ATRbeartp1:na
excol = long_short == 1 and close<ATRbulltp1?green: long_short==-1 and close>ATRbeartp1?red:color.gray
exout = plot(exin, 'TP 8', color=color.new(excol, 0), style=plot.style_circles, editable=false)
fill(entout,exout,exin,long_short==1?bullentry:long_short==-1?bearentry:na, top_color=color.new(long_short==1?darkgreen:long_short==-1?darkred:na,bgrad), bottom_color=color.new(long_short==1?darkgreen:long_short==-1?darkred:na,tgrad))
tp2out = state==1 and long_short==1?ATRbulltp2:state==2 and long_short==-1?ATRbeartp2:na
tp2col = long_short == 1 and close<ATRbulltp2?green: long_short==-1 and close>ATRbeartp2?red:color.gray
plot(tp2out, "TP 7", color=color.new(tp2col,10), style=plot.style_circles, show_last=1, editable=false)
tp3out = state==1 and long_short==1?ATRbulltp3:state==2 and long_short==-1?ATRbeartp3:na
tp3col = long_short == 1 and close<ATRbulltp3?green: long_short==-1 and close>ATRbeartp3?red:color.gray
plot(tp3out, "TP 6", color=color.new(tp3col,20), style=plot.style_circles, show_last=1, editable=false)
tp4out = state==1 and long_short==1?ATRbulltp4:state==2 and long_short==-1?ATRbeartp4:na
tp4col = long_short == 1 and close<ATRbulltp4?green: long_short==-1 and close>ATRbeartp4?red:color.gray
plot(tp4out, "TP 5", color=color.new(tp4col,30), style=plot.style_circles, show_last=1, editable=false)
tp5out = state==1 and long_short==1?ATRbulltp5:state==2 and long_short==-1?ATRbeartp5:na
tp5col = long_short == 1 and close<ATRbulltp5?green: long_short==-1 and close>ATRbeartp5?red:color.gray
plot(tp5out, "TP 4", color=color.new(tp5col,40), style=plot.style_circles, show_last=1, editable=false)
tp6out = state==1 and long_short==1?ATRbulltp6:state==2 and long_short==-1?ATRbeartp6:na
tp6col = long_short == 1 and close<ATRbulltp6?green: long_short==-1 and close>ATRbeartp6?red:color.gray
plot(tp6out, "TP 3", color=color.new(tp6col,50), style=plot.style_circles, show_last=1, editable=false)
tp7out = state==1 and long_short==1?ATRbulltp7:state==2 and long_short==-1?ATRbeartp7:na
tp7col = long_short == 1 and close<ATRbulltp7?green: long_short==-1 and close>ATRbeartp7?red:color.gray
plot(tp7out, "TP 2", color=color.new(tp7col,60), style=plot.style_circles, show_last=1, editable=false)
tp8out = state==1 and long_short==1?ATRbulltp8:state==2 and long_short==-1?ATRbeartp8:na
tp8col = long_short == 1 and close<ATRbulltp8?green: long_short==-1 and close>ATRbeartp8?red:color.gray
plot(tp8out, "TP 1", color=color.new(tp8col,60), style=plot.style_circles, show_last=1, editable=false)
dca1in=state==1 and long_short==1?vwbullse:state==2 and long_short==-1?vwbearse:na
dca1out=plot(dca1in, "DCA/Stop 1", color=color.new(color.gray, 40), style=plot.style_circles, show_last=1, editable=false)
dca2in=state==1 and long_short==1?vwbullse2:state==2 and long_short==-1?vwbearse2:na
dca2out=plot(dca2in, "DCA/Stop 2", color=color.new(color.gray, 20), style=plot.style_circles, show_last=1, editable=false)
dca3in=state==1 and long_short==1?vwbullse3:state==2 and long_short==-1?vwbearse3:na
dca3out=plot(dca3in, "DCA/Stop 3", color=color.new(color.gray, 0), style=plot.style_circles, editable=false)
fill(entout,dca3out,long_short==1?vwbullse3:long_short==-1?vwbearse3:na,long_short==1?bullentry:long_short==-1?bearentry:na, top_color=color.new(gray,85), bottom_color=color.new(gray,tgrad))
// Trade Setup Labels
// Profit
bullt1profit=(((ATRbulltp1/bullentry)- 1)*100)
beart1profit=((1-(bearentry/ATRbeartp1))*-100)
bullt2profit=(((ATRbulltp2/bullentry)- 1)*100)
beart2profit=((1-(bearentry/ATRbeartp2))*-100)
bullt3profit=(((ATRbulltp3/bullentry)- 1)*100)
beart3profit=((1-(bearentry/ATRbeartp3))*-100)
bullt4profit=(((ATRbulltp4/bullentry)- 1)*100)
beart4profit=((1-(bearentry/ATRbeartp4))*-100)
bullt5profit=(((ATRbulltp5/bullentry)- 1)*100)
beart5profit=((1-(bearentry/ATRbeartp5))*-100)
bullt6profit=(((ATRbulltp6/bullentry)- 1)*100)
beart6profit=((1-(bearentry/ATRbeartp6))*-100)
bullt7profit=(((ATRbulltp7/bullentry)- 1)*100)
beart7profit=((1-(bearentry/ATRbeartp7))*-100)
bullt8profit=(((ATRbulltp8/bullentry)- 1)*100)
beart8profit=((1-(bearentry/ATRbeartp8))*-100)
//-----------------------------Liquidation levels-----------------------------//
// @ mabonyi
i_show_x1 = input.bool(false, title='Show Liquidation Levels & Events? 🩸', group=grll)
i_nonlinear = input.bool(false, title='Inverse/Non-linear Contract', group=grll,
tooltip="A linear contract, which is a USDT-margined contract, uses USDT to make contract transactions with cryptocurrencies, and the underlying prices rise and fall linearly with revenue. Inverse/Non-linear contracts are a coin-margined contract. For example, in a BTC-margined contract, you must use Bitcoin as the underlying asset.")
i_maintmargin = input.float(0.05, title='Maintenance Margin above Liquidation', group=grll)
maint_margin = 1 - i_maintmargin
i_x1 = input.int(100, title='Leverage', minval=1, maxval=300, group=grll, tooltip="Leverage in X's. For example, if using 25x leverage, insert 25 here. Max leverage = 300x")
i_showlast = 0
i_offset = 0
i_label_offset = 0
// Calculations
f_leveraged(_price, _x) =>
_xlong = i_nonlinear ? _x + 1 : _x
_xshort = i_nonlinear ? _x - 1 : _x
_liq_long = _price * (1 - 1 / _xlong * maint_margin)
_liq_short = _price * (1 + 1 / _xshort * maint_margin)
[_liq_long, _liq_short]
f_print(_y, _txt, _c) =>
t = time_close + (i_offset + i_label_offset) * timeframe.multiplier * 60 * 1000
var _lbl = label.new(t, _y, _txt, xloc.bar_time, yloc.price, color.white, label.style_none, _c, size.small)
label.set_xy(_lbl, t, _y)
label.set_text(_lbl, _txt)
[x1_long, x1_short] = f_leveraged(close, i_x1)
// Entry Liquidation Levels
longLiquidation = ta.valuewhen(long_last, x1_long, 0)
shortLiquidation = ta.valuewhen(short_last, x1_short, 0)
// Liquidation Line Adaptive Coloring
longliqlinecol = longLiquidation<vwbullse3 ? color.yellow:brightred
shortliqlinecol = shortLiquidation>vwbearse3 ? color.yellow:brightred
llcolout= long_short == 1 ? longliqlinecol : long_short==-1 ? shortliqlinecol : na
// Liquidation Lines & Fill
llin=long_short == 1 and i_show_x1 ? longLiquidation : long_short == -1 and i_show_x1 ? shortLiquidation : na
llout=plot(llin, style=plot.style_circles, color=color.new(llcolout, 0), linewidth=1, title='Liquidation Level', editable=false)
liqfiltopcol=long_short==1 and longLiquidation < vwbullse3 ? color.new(color.yellow,85) : long_short==-1 and shortLiquidation > vwbearse3 ? color.new(color.yellow,90) : na
liqfilbotcol=long_short==1 and longLiquidation < vwbullse3 ? color.new(color.yellow,97) : long_short==-1 and shortLiquidation > vwbearse3 ? color.new(color.yellow,98) : na
fill(llout,dca3out, long_short==1?longLiquidation: long_short==-1?shortLiquidation: na, long_short==1?vwbullse3: long_short==-1?vwbearse3: na, top_color=liqfiltopcol, bottom_color=liqfilbotcol)
liqtip2 = i_show_x1 ? str.tostring(truncateprice(llin, pricedecimals)) : "None"
// Liquidation Occured?
longliqhit=(ta.crossunder(low, longLiquidation) or low<longLiquidation) and long_short==1 and i_show_x1
shortliqhit=(ta.crossover(high, shortLiquidation) or high>shortLiquidation) and long_short==-1 and i_show_x1
// Last Liquidations
leverage= i_show_x1 ? i_x1 : 1
lastlliq = "💯 Leverage: " + str.tostring(leverage) + "x\n🩸 Long Liquidation: " + str.tostring(truncateprice(longLiquidation, pricedecimals)) + "\n📅 Last Long Liquidation: " + str.tostring(ta.barssince(longliqhit[1])) + " candles"
lastsliq = "💯 Leverage: " + str.tostring(leverage) + "x\n🩸 Short Liquidation: " + str.tostring(truncateprice(shortLiquidation, pricedecimals)) + "\n📅 Last Short Liquidation: " + str.tostring(ta.barssince(shortliqhit[1])) + " candles"
// Liquidation Event
var label liqhit = na
if longliqhit and long_short==1 and i_show_x1
label.new(bar_index,low,yloc=yloc.belowbar,text='🩸',textcolor=color.gray, style=label.style_none, tooltip=lastlliq)
alertsyntax_longliq='🔔 Long Liquidated 🩸\n' + lastlliq
alert(message=alertsyntax_longliq, freq=alert_freq)
if shortliqhit and long_short==-1 and i_show_x1
label.new(bar_index,high,yloc=yloc.abovebar,text='🩸',textcolor=color.gray, style=label.style_none, tooltip=lastsliq)
alertsyntax_shortliq='🔔 Short Liquidated 🩸\n' + lastsliq
alert(message=alertsyntax_shortliq, freq=alert_freq)
// --------------------------------- Trade Labels --------------------------- //
//-------------------- Backtesting
// @ Capissimo
bidask = close
tbase = (time - time[1]) / 1000
tcurr = (timenow - time_close[1]) / 1000
barlife = tcurr / tbase
var float start_long_trade = bidask
var float long_trades = 0.
var float start_short_trade = bidask
var float short_trades = 0.
var int wins = 0
var int trade_count = 0
longtphit = ta.crossover(high, ATRbulltp1) and longBar2
longstophit = ta.crossunder(low, vwbullse3) and dcaorstop =="Stop" and longBar2
shorttphit = ta.crossunder(low, ATRbeartp1) and shortBar2
shortstophit = ta.crossover(high, vwbearse3) and dcaorstop =="Stop" and shortBar2
if bullcross //enter bull
start_long_trade := bidask
start_long_trade
if bearcross or (i_show_x1?longliqhit:na) or longtphit or (dcaorstop=="Stop"?longstophit:na)//exit bull
ldiff = bidask - start_long_trade // long profit in dollars
wins := ldiff > 0 ? 1 : 0
long_trades := ldiff * lot_size
trade_count := 1
trade_count
if bearcross //enter bear
start_short_trade := bidask
start_short_trade
if bullcross or (i_show_x1?shortliqhit:na) or shorttphit or (dcaorstop=="Stop"?shortstophit:na)//exitbear
sdiff = start_short_trade - bidask // short profit in dollars
wins := sdiff > 0 ? 1 : 0
short_trades := sdiff * lot_size
trade_count := 1
trade_count
bullcprofit=((bidask-start_long_trade)/start_long_trade)
bearcprofit=((start_short_trade-bidask)/start_short_trade)
cumbull = ta.cum(long_trades)
cumbear = ta.cum(short_trades)
cumpbull = ta.cum(bullcprofit)
cumpbear = ta.cum(bearcprofit)
cumreturn = ta.cum(long_trades) + ta.cum(short_trades) // sum of both short profit and long profit in $
cumpreturn = ta.cum(bullcprofit) + ta.cum(bearcprofit) // sum of both short profit and long profit in %
totaltrades = ta.cum(trade_count) //# trades
totalwins = ta.cum(wins)
totallosses = totaltrades - totalwins == 0 ? 1 : totaltrades - totalwins
avgreturn = cumreturn / totaltrades
avgpreturn = cumpreturn / totaltrades
avgbulltp = bullentry*(1+ta.valuewhen(bullcross,avgpreturn,0))
avgbeartp = bearentry*(1-ta.valuewhen(bearcross,avgpreturn,0))
avgtp = long_short==1?avgbulltp:long_short==-1?avgbeartp:na
avgtpcol = long_short == 1 and avgtp>bullentry?green:long_short == 1 and avgtp<bullentry?red: long_short==-1 and avgtp<bearentry?red: long_short==-1 and avgtp>bearentry?red:na
plot(avgtp, "Avg TP", color=color.new(avgtpcol,50), style=plot.style_circles)
info = "\n\n 📈 Cumulative Backtesting 📈"
+ '\nBull Profit: $ ' + str.tostring(cumbull, '#.##') +'\nBear Profit: $ ' + str.tostring(cumbear, '#.##') + '\nTotal Profit: $ ' + str.tostring(cumreturn, '#.##') + '\nAverage Total Profit: $ ' + str.tostring(avgreturn, '#.##')
+ '\nBull Return: ' + str.tostring(cumpbull, '#.## %') +'\nBear Return: ' + str.tostring(cumpbear, '#.## %') + '\nTotal Return: ' + str.tostring(cumpreturn, '#.## %') + '\nAverage Total Return: ' + str.tostring(avgpreturn, '#.## %')
+ '\nTotal Wins: ' + str.tostring(totalwins, '#') + '\nTotal Losses: ' + str.tostring(totallosses, '#') + '\n🚦 Total Trades: ' + str.tostring(totaltrades, '#') + '\nWins/Trades: ' + str.tostring(totalwins / totaltrades, '#.## %')
// Crossover profit
bullxprofit = (((close - bullentry)/bullentry)*100)
bearxprofit = (((close - bearentry)/bearentry)*-100)
curbullprof = close-bullentry
curbearprof = bearentry-close
tradelabsize = input.string(size.tiny, "Size", [size.tiny, size.small, size.normal, size.large, size.huge, size.auto], group=grt)
tradetime = ta.barssince(bullcross or bearcross)
// Plot Labels
bullentrytt = "🚦 Entry: " + (long_short==1?"🟢 Long @ ":long_short==-1?" 🔴 Short @ ":na) + str.tostring(truncateprice(bullentry, pricedecimals))
+ "\n🛑 DCA/Stop 3: " + str.tostring(truncateprice(dca3in, pricedecimals)) + "\n🩸 Liquidation: " + liqtip2
+ "\n🎯 Average Return Target: " + str.tostring(truncateprice(avgtp, pricedecimals)) + "\n🎯 Take Profit 8: " + str.tostring(truncateprice(exin, pricedecimals))
+ "\n💸 Lot Size: " + str.tostring(lot_size)
bearentrytt = "🚦 Entry: " + (long_short==1?"🟢 Long @ ":long_short==-1?" 🔴 Short @ ":na) + str.tostring(truncateprice(bearentry, pricedecimals))
+ "\n🛑 DCA/Stop 3: " + str.tostring(truncateprice(dca3in, pricedecimals)) + "\n🩸 Liquidation: " + liqtip2
+ "\n🎯 Average Return Target: " + str.tostring(truncateprice(avgtp, pricedecimals)) + "\n🎯 Take Profit 8: " + str.tostring(truncateprice(exin, pricedecimals))
+ "\n💸 Lot Size: " + str.tostring(lot_size)
var label signal = na
if bullcross
label.new(bar_index,low,yloc=yloc.belowbar,text='🚦\nLong',textcolor=color.white, style=label.style_none, tooltip=bullentrytt)
alertsyntax_golong= "🔔 Go Long 🟢\n" + bullentrytt
alert(message=alertsyntax_golong, freq=alert_freq)
if bearcross
label.new(bar_index,high,yloc=yloc.abovebar,text='🚦\nShort',textcolor=color.white, style=label.style_none, tooltip=bearentrytt)
alertsyntax_goshort= "🔔 Go Short 🔴\n" + bearentrytt
alert(message=alertsyntax_goshort, freq=alert_freq)
var label entry = na
if state==1 and long_short==1 and barstate.islast
entry := label.new(bar_index, y=bullentry, text=str.tostring(truncateprice(bullxprofit*leverage, pricedecimals)) + " %", size=tradelabsize, style=label.style_label_left, color=color.new(color.white,100), textcolor=bullxprofit>0?brightgreen:bullxprofit<0?brightred:color.gray,
tooltip=bullentrytt + "\n⌚ Trade Time: " + str.tostring(tradetime) + " candles" + "\nCurrent Bull Profit: $ " + str.tostring(curbullprof, '#.##') + "\nCurrent Bull Return: " + str.tostring(bullcprofit*leverage, '#.## %') + info)
label.delete(entry[1])
if state==1 and long_short==1 and barstate.islast and bar_update_alerts
alertsyntax_longupdate= "🔔 Long Update 🟢: " + str.tostring(truncateprice(close,pricedecimals)) + "\n⌚ Trade Time: " + str.tostring(tradetime) + " candles" + "\n💵Current Bull Profit: $ " + str.tostring(curbullprof, '#.##') + "\n📈Current Bull Return: " + str.tostring(bullcprofit*leverage, '#.## %') + "\n" + bullentrytt //+ info
alert(message=alertsyntax_longupdate, freq=alert_freq)
if state==2 and long_short==-1 and barstate.islast
entry := label.new(bar_index, y=bearentry, text=str.tostring(truncateprice(bearxprofit*leverage, pricedecimals)) + " %", size=tradelabsize, style=label.style_label_left, color=color.new(color.white,100), textcolor=bearxprofit>0?brightgreen:bearxprofit<0?brightred:color.gray,
tooltip=bearentrytt + "\n⌚ Trade Time: " + str.tostring(tradetime) + " candles" + "\nCurrent Bear Profit: $ " + str.tostring(curbearprof, '#.##') + "\nCurrent Bear Return: " + str.tostring(bearcprofit*leverage, '#.## %') + info)
label.delete(entry[1])
if state==2 and long_short==-1 and barstate.islast and bar_update_alerts
alertsyntax_shortupdate= "🔔 Short Update 🔴: " + str.tostring(truncateprice(close,pricedecimals)) + "\n⌚ Trade Time: " + str.tostring(tradetime) + " candles" + "\n💵Current Bear Profit: $ " + str.tostring(curbearprof, '#.##') + "\n📈Current Bear Return: " + str.tostring(bearcprofit*leverage, '#.## %') + "\n" + bearentrytt //+ info
alert(message=alertsyntax_shortupdate, freq=alert_freq)
var label tp1 = na
if state==1 and long_short==1 and barstate.islast
tp1 := label.new(bar_index, y=ATRbulltp1 , text=str.tostring(truncateprice(ATRbulltp1 , pricedecimals)), size=tradelabsize, style=label.style_label_left, color=color.new(color.white,100), textcolor=green, tooltip="🎯: " + str.tostring(truncateprice(ATRbulltp1, pricedecimals)) + "\nProfit: " + str.tostring(truncateprice(bullt1profit*leverage, pricedecimals)) + " %\n" + str.tostring(truncateprice(atrMultiplier, pricedecimals)) + "x "+ "ATR " + str.tostring(atrPeriod))
label.delete(tp1[1])
if state==2 and long_short==-1 and barstate.islast
tp1 := label.new(bar_index, y=ATRbeartp1 , text=str.tostring(truncateprice(ATRbeartp1 , pricedecimals)), size=tradelabsize, style=label.style_label_left, color=color.new(color.white,100), textcolor=red, tooltip="🎯: " + str.tostring(truncateprice(ATRbeartp1, pricedecimals)) + "\nProfit: " + str.tostring(truncateprice(beart1profit*leverage, pricedecimals)) + " %\n" + str.tostring(truncateprice(atrMultiplier, pricedecimals)) + "x " + "ATR " + str.tostring(atrPeriod))
label.delete(tp1[1])
var label tp2 = na
if state==1 and long_short==1 and barstate.islast
tp2 := label.new(bar_index, y=ATRbulltp2, text=str.tostring(truncateprice(ATRbulltp2, pricedecimals)), size=tradelabsize, style=label.style_label_left, color=color.new(color.white,100), textcolor=color.new(close<ATRbulltp2?green:gray,10), tooltip="🎯: " + str.tostring(truncateprice(ATRbulltp2, pricedecimals)) + "\nProfit: " + str.tostring(truncateprice(bullt2profit*leverage, pricedecimals)) + " %\n" + str.tostring(truncateprice(atrMultiplier*0.854, pricedecimals)) + "x " + "ATR " + str.tostring(atrPeriod))
label.delete(tp2[1])
if state==2 and long_short==-1 and barstate.islast
tp2 := label.new(bar_index, y=ATRbeartp2, text=str.tostring(truncateprice(ATRbeartp2, pricedecimals)), size=tradelabsize, style=label.style_label_left, color=color.new(color.white,100), textcolor=color.new(close>ATRbeartp2?red:gray,10), tooltip="🎯: " + str.tostring(truncateprice(ATRbeartp2, pricedecimals)) + "\nProfit: " + str.tostring(truncateprice(beart2profit*leverage, pricedecimals)) + " %\n" + str.tostring(truncateprice(atrMultiplier*0.854, pricedecimals)) + "x " + "ATR "+ str.tostring(atrPeriod))
label.delete(tp2[1])
var label tp3 = na
if state==1 and long_short==1 and barstate.islast
tp3 := label.new(bar_index, y=ATRbulltp3, text=str.tostring(truncateprice(ATRbulltp3, pricedecimals)), size=tradelabsize, style=label.style_label_left, color=color.new(color.white,100), textcolor=color.new(close<ATRbulltp3?green:gray,20), tooltip="🎯: " + str.tostring(truncateprice(ATRbulltp3, pricedecimals)) + "\nProfit: " + str.tostring(truncateprice(bullt3profit*leverage, pricedecimals)) + " %\n" + str.tostring(truncateprice(atrMultiplier*0.763, pricedecimals)) + "x " + "ATR " + str.tostring(atrPeriod))
label.delete(tp3[1])
if state==2 and long_short==-1 and barstate.islast
tp3 := label.new(bar_index, y=ATRbeartp3, text=str.tostring(truncateprice(ATRbeartp3, pricedecimals)), size=tradelabsize, style=label.style_label_left, color=color.new(color.white,100), textcolor=color.new(close>ATRbeartp3?red:gray,20), tooltip="🎯: " + str.tostring(truncateprice(ATRbeartp3, pricedecimals)) + "\nProfit: " + str.tostring(truncateprice(beart3profit*leverage, pricedecimals)) + " %\n" + str.tostring(truncateprice(atrMultiplier*0.763, pricedecimals)) + "x " + "ATR " + str.tostring(atrPeriod))
label.delete(tp3[1])
var label tp4 = na
if state==1 and long_short==1 and barstate.islast
tp4 := label.new(bar_index, y=ATRbulltp4, text=str.tostring(truncateprice(ATRbulltp4, pricedecimals)), size=tradelabsize, style=label.style_label_left, color=color.new(color.white,100), textcolor=color.new(close<ATRbulltp4?green:gray,30), tooltip="🎯: " + str.tostring(truncateprice(ATRbulltp4, pricedecimals)) + "\nProfit: " + str.tostring(truncateprice(bullt4profit*leverage, pricedecimals)) + " %\n" + str.tostring(truncateprice(atrMultiplier*0.618, pricedecimals)) + "x " + "ATR " + str.tostring(atrPeriod))
label.delete(tp4[1])
if state==2 and long_short==-1 and barstate.islast
tp4 := label.new(bar_index, y=ATRbeartp4, text=str.tostring(truncateprice(ATRbeartp4, pricedecimals)), size=tradelabsize, style=label.style_label_left, color=color.new(color.white,100), textcolor=color.new(close>ATRbeartp4?red:gray, 30), tooltip="🎯: " + str.tostring(truncateprice(ATRbeartp4, pricedecimals)) + "\nProfit: " + str.tostring(truncateprice(beart4profit*leverage, pricedecimals)) + " %\n" + str.tostring(truncateprice(atrMultiplier*0.618, pricedecimals)) + "x " + "ATR " + str.tostring(atrPeriod))
label.delete(tp4[1])
var label tp5 = na
if state==1 and long_short==1 and barstate.islast
tp5 := label.new(bar_index, y=ATRbulltp5, text=str.tostring(truncateprice(ATRbulltp5, pricedecimals)), size=tradelabsize, style=label.style_label_left, color=color.new(color.white,100), textcolor=color.new(close<ATRbulltp5?green:gray, 40), tooltip="🎯: " + str.tostring(truncateprice(ATRbulltp5, pricedecimals)) + "\nProfit: " + str.tostring(truncateprice(bullt5profit*leverage, pricedecimals)) + " %\n" + str.tostring(truncateprice(atrMultiplier*0.5, pricedecimals)) + "x " + "ATR " + str.tostring(atrPeriod))
label.delete(tp5[1])
if state==2 and long_short==-1 and barstate.islast
tp5 := label.new(bar_index, y=ATRbeartp5, text=str.tostring(truncateprice(ATRbeartp5, pricedecimals)), size=tradelabsize, style=label.style_label_left, color=color.new(color.white,100), textcolor=color.new(close>ATRbeartp5?red:gray, 40), tooltip="🎯: " + str.tostring(truncateprice(ATRbeartp5, pricedecimals)) + "\nProfit: " + str.tostring(truncateprice(beart5profit*leverage, pricedecimals)) + " %\n" + str.tostring(truncateprice(atrMultiplier*0.5, pricedecimals)) + "x " + "ATR "+ str.tostring(atrPeriod))
label.delete(tp5[1])
var label tp6 = na
if state==1 and long_short==1 and barstate.islast
tp6 := label.new(bar_index, y=ATRbulltp6, text=str.tostring(truncateprice(ATRbulltp6, pricedecimals)), size=tradelabsize, style=label.style_label_left, color=color.new(color.white,100), textcolor=color.new(close<ATRbulltp6?green:gray, 50), tooltip="🎯: " + str.tostring(truncateprice(ATRbulltp6, pricedecimals)) + "\nProfit: " + str.tostring(truncateprice(bullt6profit*leverage, pricedecimals)) + " %\n" + str.tostring(truncateprice(atrMultiplier*0.382, pricedecimals)) + "x " + "ATR " + str.tostring(atrPeriod))
label.delete(tp6[1])
if state==2 and long_short==-1 and barstate.islast
tp6 := label.new(bar_index, y=ATRbeartp6, text=str.tostring(truncateprice(ATRbeartp6, pricedecimals)), size=tradelabsize, style=label.style_label_left, color=color.new(color.white,100), textcolor=color.new(close>ATRbeartp6?red:gray,50), tooltip="🎯: " + str.tostring(truncateprice(ATRbeartp6, pricedecimals)) + "\nProfit: " + str.tostring(truncateprice(beart6profit*leverage, pricedecimals)) + " %\n" + str.tostring(truncateprice(atrMultiplier*0.382, pricedecimals)) + "x " + "ATR " + str.tostring(atrPeriod))
label.delete(tp6[1])
var label tp7 = na
if state==1 and long_short==1 and barstate.islast
tp7 := label.new(bar_index, y=ATRbulltp7, text=str.tostring(truncateprice(ATRbulltp7, pricedecimals)), size=tradelabsize, style=label.style_label_left, color=color.new(color.white,100), textcolor=color.new(close<ATRbulltp7?green:gray,60), tooltip="🎯: " + str.tostring(truncateprice(ATRbulltp7, pricedecimals)) + "\nProfit: " + str.tostring(truncateprice(bullt7profit*leverage, pricedecimals)) + " %\n" + str.tostring(truncateprice(atrMultiplier*0.236, pricedecimals)) + "x " + "ATR "+ str.tostring(atrPeriod))
label.delete(tp7[1])
if state==2 and long_short==-1 and barstate.islast
tp7 := label.new(bar_index, y=ATRbeartp7, text=str.tostring(truncateprice(ATRbeartp7, pricedecimals)), size=tradelabsize, style=label.style_label_left, color=color.new(color.white,100), textcolor=color.new(close>ATRbeartp7?red:gray,60), tooltip="🎯: " + str.tostring(truncateprice(ATRbeartp7, pricedecimals)) + "\nProfit: " + str.tostring(truncateprice(beart7profit*leverage, pricedecimals)) + " %\n" + str.tostring(truncateprice(atrMultiplier*0.236, pricedecimals)) + "x " + "ATR " + str.tostring(atrPeriod))
label.delete(tp7[1])
var label tp8 = na
if state==1 and long_short==1 and barstate.islast
tp8 := label.new(bar_index, y=ATRbulltp8, text=str.tostring(truncateprice(ATRbulltp8, pricedecimals)), size=tradelabsize, style=label.style_label_left, color=color.new(color.white,100), textcolor=color.new(close<ATRbulltp8?green:gray,70), tooltip="🎯: " + str.tostring(truncateprice(ATRbulltp8, pricedecimals)) + "\nProfit: " + str.tostring(truncateprice(bullt8profit*leverage, pricedecimals)) + " %\n" + str.tostring(truncateprice(atrMultiplier*0.146, pricedecimals)) + "x " + "ATR "+ str.tostring(atrPeriod))
label.delete(tp8[1])
if state==2 and long_short==-1 and barstate.islast
tp8 := label.new(bar_index, y=ATRbeartp8, text=str.tostring(truncateprice(ATRbeartp8, pricedecimals)), size=tradelabsize, style=label.style_label_left, color=color.new(color.white,100), textcolor=color.new(close>ATRbeartp8?red:gray,70), tooltip="🎯: " + str.tostring(truncateprice(ATRbeartp8, pricedecimals)) + "\nProfit: " + str.tostring(truncateprice(beart8profit*leverage, pricedecimals)) + " %\n" + str.tostring(truncateprice(atrMultiplier*0.146, pricedecimals)) + "x " + "ATR "+ str.tostring(atrPeriod))
label.delete(tp8[1])
var label dca1 = na
if state==1 and long_short==1 and barstate.islast
dca1 := label.new(bar_index, y=vwbullse, text=str.tostring(truncateprice(vwbullse, pricedecimals)), size=tradelabsize, style=label.style_label_left, color=color.new(color.white,100), textcolor=color.new(color.gray, 40), tooltip="📍: " + str.tostring(truncateprice(vwbullse, pricedecimals)) + "\n-" + str.tostring(truncateprice(atrMultiplier*0.146, pricedecimals)) + "x " + "ATR " + str.tostring(atrPeriod)) //, tooltip=str.tostring(truncateprice(bullt8profit, pricedecimals)) + " %")
label.delete(dca1[1])
if state==2 and long_short==-1 and barstate.islast
dca1 := label.new(bar_index, y=vwbearse, text=str.tostring(truncateprice(vwbearse, pricedecimals)), size=tradelabsize, style=label.style_label_left, color=color.new(color.white,100), textcolor=color.new(color.gray, 40), tooltip="📍: " + str.tostring(truncateprice(vwbearse, pricedecimals)) + "\n-" + str.tostring(truncateprice(atrMultiplier*0.146, pricedecimals)) + "x " + "ATR " + str.tostring(atrPeriod)) //, tooltip=str.tostring(truncateprice(beart8profit, pricedecimals)) + " %")
label.delete(dca1[1])
var label dca2 = na
if state==1 and long_short==1 and barstate.islast
dca2 := label.new(bar_index, y=vwbullse2, text=str.tostring(truncateprice(vwbullse2, pricedecimals)), size=tradelabsize, style=label.style_label_left, color=color.new(color.white,100), textcolor=color.new(color.gray, 20), tooltip="📍: " + str.tostring(truncateprice(vwbullse2, pricedecimals)) + "\n-" + str.tostring(truncateprice(atrMultiplier*0.236, pricedecimals)) + "x " + "ATR " + str.tostring(atrPeriod)) //, tooltip=str.tostring(truncateprice(bullt8profit, pricedecimals)) + " %")
label.delete(dca2[1])
if state==2 and long_short==-1 and barstate.islast
dca2 := label.new(bar_index, y=vwbearse2, text=str.tostring(truncateprice(vwbearse2, pricedecimals)), size=tradelabsize, style=label.style_label_left, color=color.new(color.white,100), textcolor=color.new(color.gray, 20), tooltip="📍: " + str.tostring(truncateprice(vwbearse2, pricedecimals)) + "\n-" + str.tostring(truncateprice(atrMultiplier*0.236, pricedecimals)) + "x " + "ATR " + str.tostring(atrPeriod)) //, tooltip=str.tostring(truncateprice(beart8profit, pricedecimals)) + " %")
label.delete(dca2[1])
var label dca3 = na
if state==1 and long_short==1 and barstate.islast
dca3 := label.new(bar_index, y=vwbullse3, text=str.tostring(truncateprice(vwbullse3, pricedecimals)), size=tradelabsize, style=label.style_label_left, color=color.new(color.white,100), textcolor=color.new(color.gray, 0), tooltip="📍: " + str.tostring(truncateprice(vwbullse3, pricedecimals)) + "\n-" + str.tostring(truncateprice(atrMultiplier*0.382, pricedecimals)) + "x " + "ATR " + str.tostring(atrPeriod)) //, tooltip=str.tostring(truncateprice(bullt8profit, pricedecimals)) + " %")
label.delete(dca3[1])
if state==2 and long_short==-1 and barstate.islast
dca3 := label.new(bar_index, y=vwbearse3, text=str.tostring(truncateprice(vwbearse3, pricedecimals)), size=tradelabsize, style=label.style_label_left, color=color.new(color.white,100), textcolor=color.new(color.gray, 0), tooltip="📍: " + str.tostring(truncateprice(vwbearse3, pricedecimals)) + "\n-" + str.tostring(truncateprice(atrMultiplier*0.382, pricedecimals)) + "x " + "ATR " + str.tostring(atrPeriod)) //, tooltip=str.tostring(truncateprice(beart8profit, pricedecimals)) + " %")
label.delete(dca3[1])
var label cp = na
if state==1 and long_short==0 and barstate.islast
cp := label.new(bar_index, y=high, text=str.tostring(truncateprice(bullxprofit*leverage, pricedecimals)) + " %", size=tradelabsize, style=label.style_label_left, color=color.new(color.white,100), textcolor=color.new(green,0), tooltip="🚦 Entry: " + str.tostring(truncateprice(bullentry, pricedecimals)) + "\n💵 Current Profit: $ " + str.tostring(curbullprof, '#.##') + "\n📈 Current Return: " + str.tostring(bullcprofit*leverage, '#.## %') + (i_show_x1?("\n💯 Leverage: " + str.tostring(leverage) + "x"):na) + info) // + (automan=="Auto"?optMAtip:na) + info) //, tooltip=str.tostring(truncateprice(bullt8profit, pricedecimals)) + " %")
label.delete(cp[1])
if state==2 and long_short==0 and barstate.islast
cp := label.new(bar_index, y=low, text=str.tostring(truncateprice(bearxprofit*leverage, pricedecimals)) + " %", size=tradelabsize, style=label.style_label_left, color=color.new(color.white,100), textcolor=color.new(red,0), tooltip="🚦 Entry: " + str.tostring(truncateprice(bearentry, pricedecimals)) + "\n💵 Current Profit: $ " + str.tostring(curbearprof, '#.##') + "\n📈 Current Return: " + str.tostring(bearcprofit*leverage, '#.## %')+ (i_show_x1?("\n💯 Leverage: " + str.tostring(leverage) + "x"):na) + info) // + (automan=="Auto"?optMAtip:na) + info) //, tooltip=str.tostring(truncateprice(beart8profit, pricedecimals)) + " %")
label.delete(cp[1])
var label liq = na
if state==1 and long_short==1 and i_show_x1 and barstate.islast
liq := label.new(bar_index, y=longLiquidation, text=str.tostring(truncateprice(longLiquidation, pricedecimals)), size=tradelabsize, style=label.style_label_left, color=color.new(color.white,100), textcolor= longLiquidation < vwbullse3 ? color.yellow : brightred, tooltip=lastlliq)
label.delete(liq[1])
if state==2 and long_short==-1 and i_show_x1 and barstate.islast
liq := label.new(bar_index, y=shortLiquidation, text=str.tostring(truncateprice(shortLiquidation, pricedecimals)), size=tradelabsize, style=label.style_label_left, color=color.new(color.white,100), textcolor= shortLiquidation > vwbearse3 ? color.yellow : brightred, tooltip=lastsliq)
label.delete(liq[1])
//------------Reset long_short if SL/TP hit during bar------------------------//
tpreset = true
longclose = longtphit or longstophit
shortclose = shorttphit or shortstophit
bullstopp = ((vwbullse3 - bullentry)/bullentry)*100
bearstopp = ((bearentry - vwbearse3)/bearentry)*100
bulltpp = ((ATRbulltp1 - bullentry)/bullentry)*100
beartpp = ((bearentry - ATRbeartp1)/bearentry)*100
tradesetuptt = "🚦 Entry: " + (long_short==1?"🟢 Long @ ":long_short==-1?" 🔴 Short @ ":na) + str.tostring(truncateprice(entin,pricedecimals)) +
"\n🛑 DCA/Stop 3: " + str.tostring(truncateprice(dca3in, pricedecimals)) +
"\n🩸 Liquidation: " + liqtip2 +
"\n💰 Take Profit 8: " + str.tostring(truncateprice(exin,pricedecimals)) +
"\n📈 Return: " + str.tostring(truncateprice((long_short==1?bullstopp:long_short==-1?bearstopp:na)*leverage,pricedecimals)) + " %" +
"\n💵 Loss * "+ str.tostring(lot_size) + " lots: $ " + str.tostring(truncateprice(long_short==1?(vwbullse3 - bullentry):long_short==-1?(bearentry - vwbearse3):na,pricedecimals)) +
"\n⌚ Trade Time: " + str.tostring(tradetime)
tradesetuptt2 = "🚦 Entry: " + (long_short==1?"🟢 Long @ ":long_short==-1?" 🔴 Short @ ":na) + str.tostring(truncateprice(entin,pricedecimals)) +
"\n🛑 DCA/Stop 3: " + str.tostring(truncateprice(dca3in, pricedecimals)) +
"\n🩸 Liquidation: " + liqtip2 +
"\n💰 Take Profit 8: " + str.tostring(truncateprice(exin,pricedecimals)) +
"\n📈 Return: " + str.tostring(truncateprice((long_short==1?bulltpp:long_short==-1?beartpp:na)*leverage,pricedecimals)) + " %" +
"\n💵 Profit * "+ str.tostring(lot_size) + " lots: $ " + str.tostring(truncateprice(long_short==1?((ATRbulltp1 - bullentry)):long_short==-1?((bearentry - ATRbeartp1)):na,pricedecimals)) +
"\n⌚ Trade Time: " + str.tostring(tradetime)
// loss labels
var label tclose = na
if longstophit and long_short==1
label.new(bar_index,low,yloc=yloc.belowbar,text='❌',textcolor=color.gray, style=label.style_none, tooltip=tradesetuptt)
alertsyntax_longstop='🔔 Long Stopped ❌\n' + tradesetuptt
alert(message=alertsyntax_longstop, freq=alert_freq)
if shortstophit and long_short==-1
label.new(bar_index,high,yloc=yloc.abovebar,text='❌',textcolor=color.gray, style=label.style_none, tooltip=tradesetuptt)
alertsyntax_shortstop='🔔 Short Stopped ❌\n' + tradesetuptt
alert(message=alertsyntax_shortstop, freq=alert_freq)
// profit labels
var label tphit = na
if longtphit and long_short==1
label.new(bar_index,high,yloc=yloc.abovebar,text='💰',textcolor=color.gray, style=label.style_none,
tooltip=tradesetuptt2)
alertsyntax_longtp='🔔 Long Take Profit 💰\n' + tradesetuptt2
alert(message=alertsyntax_longtp, freq=alert_freq)
if shorttphit and long_short==-1
label.new(bar_index,low,yloc=yloc.belowbar,text='💰',textcolor=color.gray, style=label.style_none,
tooltip=tradesetuptt2)
alertsyntax_shorttp='🔔 Long Take Profit 💰\n' + tradesetuptt2
alert(message=alertsyntax_shorttp, freq=alert_freq)
long_short := (long_short == 1 or long_short == 0) and (longclose or longliqhit) and tpreset ? 0 : (long_short == -1 or long_short == 0) and (shortclose or shortliqhit) and tpreset ? 0 : long_short
bgcol2 = state==1 and state[1]==2 ?color.green : state==2 and state[1]==1 ? color.red :na
bgcolor(color.new(bgcol2,85))
// EoS made w/ ❤ by @BarefootJoey ✌💗📈 |
Dark Energy Divergence Oscillator | https://www.tradingview.com/script/ktP4bBqu-Dark-Energy-Divergence-Oscillator/ | DarklyEnergized | https://www.tradingview.com/u/DarklyEnergized/ | 253 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ka1n0s
// Dark Energy Divergence Oscillator
// DEDO, pronounced "deed-oh"
//@version=5
indicator("Dark Energy Divergence Oscillator", "DEDO")
//INPUTS ----------------------------------------------------------------------------
// Uncomment and use the input var for dedo_symbol if desired.
// Allows DEDO to chart a symbol different than the current chart symbol
//dedo_symbol = input.symbol("SPX", "DEDO Symbol", "The symbol to analyze with DEDO")
dedo_symbol = syminfo.tickerid
// helper function to calculate plot colors
oscillator_gradient_color(signal, high_color, low_color) =>
signal_max = ta.max(signal)
signal_min = ta.min(signal)
bull_color = color.from_gradient(signal, 0, signal_max, color.new(high_color, 60), color.new(high_color, 0))
bear_color = color.from_gradient(signal, signal_min, 0, color.new(low_color, 0), color.new(low_color, 60))
osc_color = signal < 0 ? bear_color : bull_color
use_pre_ponzi_offset = input.bool(false, "Use Pre-Ponzification Offset", "Uses the DEDO Symbol price at the pre-ponzi date (pre-QE 9/9/2008 is default) to factor into the calculation against current liquidity", group = "Ponzi Settings")
pre_ponzi_date = input.time(timestamp('2008-9-9 10:00 GMT-3'), 'Ponzi Start Date', "The date to sample price used in the ponzification offset calculation. Subtracts this price first before normalization against liquidity factors", group = "Ponzi Settings")
// CB Assets
include_jpy = input.bool(false, "JPY Assets", group = "Non-US Central Bank Liquidity")
include_cny = input.bool(false, "CNY Assets", group = "Non-US Central Bank Liquidity")
include_uk = input.bool(false, "UK Assets", group = "Non-US Central Bank Liquidity")
include_snb = input.bool(false, "SNB Assets", group = "Non-US Central Bank Liquidity")
include_ecb = input.bool(false, "ECB Assets", group = "Non-US Central Bank Liquidity")
include_krc = input.bool(false, "KRC Assets", group = "Non-US Central Bank Liquidity")
include_cad = input.bool(false, "CAD Assets", group = "Non-US Central Bank Liquidity")
include_wshoicl = input.bool(true, "Inflation Compensation (WSHOICL)", "Include Fed 'Inflation Compensation' (WSHOICL) from assets portion of balance sheet", group = "Include Fed Balance Sheet Items")
include_wupsho = input.bool(true, "Unamortized Premiums (WUPSHO)", "Include Fed 'Unamortized Premiums' (WUPSHO) from assets portion of balance sheet", group = "Include Fed Balance Sheet Items")
include_wlcfll = input.bool(true, "Loans (WLCFLL)", "Include Fed 'Loans' (WLCFLL) from assets portion of balance sheet", group = "Include Fed Balance Sheet Items")
// Allocation table helper
show_allocation_table = input.bool(true, "Show Asset Allocation Table", "Show a table that provides liquidity allocation info, and suggests CB allocation settings are sufficient to support the market cap of the DEDO symbol being evaluated", group = "Table Settings")
// Multiplier to make the final values more readable. Different symbols will produced varied results.
dedo_multiplier = input.float(100.0, "Multiplier",1.0,1000, 1.0, group = "Chart Settings")
// END INPUTS ----------------------------------------------------------------------------
// HELPER METHODS ------------------------------------------------------------------------
billions_str(value) =>
"$" + str.tostring(value/1000000000, format.mintick) + " B"
// END HELPER METHODS --------------------------------------------------------------------
// FED BS
line_wresbal = request.security("FRED:WRESBAL", "D", close, currency = currency.USD)
// Optional factors on Fed balance sheet
line_fed_wshoicl = request.security("WSHOICL", "D", close, currency = currency.USD)
line_fed_wupsho = request.security("WUPSHO", "D", close, currency = currency.USD)
line_fed_wlcfll = request.security("WLCFLL", "D", close, currency = currency.USD)
// Non US CENTRAL BANK ASSETS
line_japan = request.security("FRED:JPNASSETS * FX_IDC:JPYUSD", "D", close, currency = currency.USD)
line_china = request.security("CNCBBS * FX_IDC:CNYUSD", "D", close, currency = currency.USD)
line_uk = request.security("GBCBBS * FX:GBPUSD", "D", close, currency = currency.USD)
line_ecb = request.security("ECBASSETSW * FX:EURUSD", "D", close, currency = currency.USD)
line_snb = request.security("CHCBBS", "D", close, currency = currency.USD)
line_krc = request.security("ECONOMICS:KRCBBS*FX_IDC:KRWUSD", "D", close, currency = currency.USD)
line_cad = request.security("CACBBS * CADUSD", "D", close, currency = currency.USD)
// FED subtractions
wshoicl_final = (include_wshoicl ? 0 : line_fed_wshoicl)
wupsho_final = (include_wupsho ? 0 : line_fed_wupsho)
wlcfll_final = (include_wlcfll ? 0 : line_fed_wlcfll)
subtractions_total = wlcfll_final + wupsho_final + wshoicl_final
// Apply offsets to Fed liquidity total
fed_final = line_wresbal - subtractions_total
// conditionally determine which CB assets are used in the total liquidity pool based on user settings
jpy_final = (include_jpy ? line_japan : 0)
cny_final = (include_cny ? line_china : 0)
gbp_final = (include_uk ? line_uk : 0)
snb_final = (include_snb ? line_snb : 0)
ecb_final = (include_ecb ? line_ecb : 0)
krc_final = (include_krc ? line_krc : 0)
cad_final = (include_cad ? line_cad : 0)
//
non_us_total = jpy_final + cny_final + gbp_final + snb_final + ecb_final + krc_final + cad_final
liquidity_total = fed_final + non_us_total
cb_assets_max_allocated = ta.max(liquidity_total)
norm_total_cb = liquidity_total / cb_assets_max_allocated
//plot(norm_total_cb, "norm-tot", color.red)
dedo_symbol_o = request.security(dedo_symbol,timeframe.period, open, currency = currency.USD)
dedo_symbol_h = request.security(dedo_symbol,timeframe.period, high, currency = currency.USD)
dedo_symbol_l = request.security(dedo_symbol,timeframe.period, low, currency = currency.USD)
dedo_symbol_c = request.security(dedo_symbol,timeframe.period, close, currency = currency.USD)
period = time >= pre_ponzi_date and time[1] < pre_ponzi_date
pre_ponzi = use_pre_ponzi_offset ? ta.valuewhen(period, dedo_symbol_c, 0) : 0
// Debug plot to see the value
//plot(pre_ponzi, "pre-ponz", color.white)
dedo_series_open = (norm_total_cb - ((dedo_symbol_o - pre_ponzi)/(ta.max(dedo_symbol_o) - pre_ponzi))) * dedo_multiplier
dedo_series_high = (norm_total_cb - ((dedo_symbol_h - pre_ponzi)/(ta.max(dedo_symbol_h) - pre_ponzi))) * dedo_multiplier
dedo_series_low = (norm_total_cb - ((dedo_symbol_l - pre_ponzi)/(ta.max(dedo_symbol_l) - pre_ponzi))) * dedo_multiplier
dedo_series_close = (norm_total_cb - ((dedo_symbol_c - pre_ponzi)/(ta.max(dedo_symbol_c) - pre_ponzi))) * dedo_multiplier
dedo_zero_price = norm_total_cb * (ta.max(dedo_symbol_h) - pre_ponzi) + pre_ponzi
candle_color = dedo_series_close >= dedo_series_open ? color.lime : color.red
wick_color = dedo_series_close >= dedo_series_open ? color.new(color.lime, 25) : color.new(color.red, 25)
// Plot candles for dedo signal
plotcandle(dedo_series_open, dedo_series_high, dedo_series_low, dedo_series_close, title = "Candle Chart", color = color.new(candle_color, 60), wickcolor = wick_color, bordercolor = candle_color)
plot(dedo_series_close, title = "Line Chart", linewidth = 2, color = oscillator_gradient_color(dedo_series_close, color.green, color.red), trackprice = true, display = display.none)
// Zero Bound
hline(0)
// Get the shares outstanding to calculate the mkt cap of the dedo symbol
tso = nz(request.financial(str.tostring(dedo_symbol), "TOTAL_SHARES_OUTSTANDING", "FQ", ignore_invalid_symbol=true))
mkt_cap = (na(tso) ? 0 : tso * dedo_symbol_c)
if show_allocation_table
var table mkt_cap_liquidity_tbl = table.new(position.bottom_right, 4, 2, frame_color = color.gray, bgcolor = color.gray, border_width = 1, frame_width = 1, border_color = color.white)
// Header
table.cell(mkt_cap_liquidity_tbl, 0, 0, "Total CB Liquidity", bgcolor = color.white)
table.cell(mkt_cap_liquidity_tbl, 1, 0, "Mkt Cap " + str.tostring(dedo_symbol), bgcolor = color.white)
table.cell(mkt_cap_liquidity_tbl, 2, 0, "Mkt Cap % Total CB Assets", bgcolor = color.white)
table.cell(mkt_cap_liquidity_tbl, 3, 0, "DEDO 0 Price", bgcolor = color.white)
// fill the table
table.cell(mkt_cap_liquidity_tbl, 0, 1, billions_str(liquidity_total), bgcolor = color.white)
table.cell(mkt_cap_liquidity_tbl, 1, 1, mkt_cap == 0 ? "N/A" : billions_str(mkt_cap), bgcolor = color.white)
// create a string that indicates mkt cap % of total liquidity
mkt_cap_pct_str = mkt_cap == 0 ? "N/A" : str.tostring(mkt_cap/nz(liquidity_total)*100, format.percent)
table.cell(mkt_cap_liquidity_tbl, 2, 1, mkt_cap_pct_str, bgcolor = color.white)
// DEDO zero price cell
table.cell(mkt_cap_liquidity_tbl, 3, 1, "$" + str.tostring(dedo_zero_price,format.mintick), bgcolor = color.white) |
ICT Macros | https://www.tradingview.com/script/eeNLuJQ4-ICT-Macros/ | reastruth | https://www.tradingview.com/u/reastruth/ | 1,300 | 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/
// © reastruth
//@version=4
_macroColor = input(title="Macro Color", type=input.color, defval=color.black)
_londonColor = input(title="London Macro Color", type=input.color, defval=color.black)
_dtccColor = input(title="", type=input.color, defval=color.rgb(54, 58, 69, 35))
study(title = "MACROS", overlay = true)
//New York Time
_2_33AM = timestamp("UTC-4", year, month, dayofmonth, 2, 33, 00)
_3AM = timestamp("UTC-4", year, month, dayofmonth, 3, 0, 00)
_4_03AM = timestamp("UTC-4", year, month, dayofmonth, 4, 3, 00)
_4_30AM = timestamp("UTC-4", year, month, dayofmonth, 4, 30, 00)
_2_10PM = timestamp("UTC-4", year, month, dayofmonth, 14, 10, 00)
_2_40PM = timestamp("UTC-4", year, month, dayofmonth, 14, 40, 00)
_3_15PM = timestamp("UTC-4", year, month, dayofmonth, 15, 15, 00)
_3_45PM = timestamp("UTC-4", year, month, dayofmonth, 15, 45, 00)
_8_50AM = timestamp("UTC-4", year, month, dayofmonth, 8, 50, 00)
_9_10AM = timestamp("UTC-4", year, month, dayofmonth, 9, 10, 00)
_9_50AM = timestamp("UTC-4", year, month, dayofmonth, 9, 50, 00)
_10_10AM = timestamp("UTC-4", year, month, dayofmonth, 10, 10, 00)
_1050AM = timestamp("UTC-4",year, month, dayofmonth, 10, 50, 00)
_1110AM = timestamp("UTC-4",year, month, dayofmonth, 11, 10, 00)
_1150AM = timestamp("UTC-4",year, month, dayofmonth, 11, 50, 00)
_1210PM = timestamp("UTC-4",year, month, dayofmonth, 12, 10, 00)
_1_10PM = timestamp("UTC-4",year, month, dayofmonth, 13, 10, 00)
_1_40PM = timestamp("UTC-4",year, month, dayofmonth, 13, 40, 00)
_8PM = timestamp("UTC-4",year, month, dayofmonth, 21, 00, 00)
_845PM = timestamp("UTC-4",year, month, dayofmonth, 21, 45, 00)
//2 Minute Warning
_2_30AM = timestamp("UTC-4", year, month, dayofmonth, 2, 30, 00)
_2_57AM = timestamp("UTC-4", year, month, dayofmonth, 2, 57, 00)
_3_00AM = timestamp("UTC-4", year, month, dayofmonth, 3, 0, 00)
_4_00AM = timestamp("UTC-4", year, month, dayofmonth, 4, 0, 00)
_4_27AM = timestamp("UTC-4", year, month, dayofmonth, 4, 27, 00)
_2_07PM = timestamp("UTC-4", year, month, dayofmonth, 14, 7, 00)
_2_37PM = timestamp("UTC-4", year, month, dayofmonth, 14, 37, 00)
_3_12PM = timestamp("UTC-4", year, month, dayofmonth, 15, 12, 00)
_3_42PM = timestamp("UTC-4", year, month, dayofmonth, 15, 42, 00)
_8_47AM = timestamp("UTC-4", year, month, dayofmonth, 8, 47, 00)
_9_07AM = timestamp("UTC-4", year, month, dayofmonth, 9, 7, 00)
_9_47AM = timestamp("UTC-4", year, month, dayofmonth, 9, 47, 00)
_10_07AM = timestamp("UTC-4", year, month, dayofmonth, 10, 7, 00)
_10_47AM = timestamp("UTC-4",year, month, dayofmonth, 10, 47, 00)
_11_07AM = timestamp("UTC-4",year, month, dayofmonth, 11, 7, 00)
_11_47AM = timestamp("UTC-4",year, month, dayofmonth, 11, 47, 00)
_12_07PM = timestamp("UTC-4",year, month, dayofmonth, 12, 7, 00)
_1_07PM = timestamp("UTC-4",year, month, dayofmonth, 13, 7, 00)
_1_37PM = timestamp("UTC-4",year, month, dayofmonth, 13, 37, 00)
_7_57PM = timestamp("UTC-4",year, month, dayofmonth, 19, 57, 00)
_8_42PM = timestamp("UTC-4",year, month, dayofmonth, 20, 42, 00)
// vertical line function
verticalLine(Color) =>
line.new(bar_index, low - tr, bar_index, high + tr, xloc.bar_index, extend.both, Color, line.style_dotted, 1)
// vertical line label
verticalLabel(Color, Text) =>
label.new(bar_index, high+tr, text=Text, textcolor=Color, style=label.style_none)
// M.O.
if(time==_8_50AM or time==_9_50AM or time==_1050AM or time==_1_10PM or time==_3_15PM or time==_1150AM)
verticalLine(_macroColor)
verticalLabel(_macroColor, "M.O.")
// M.C.
if(time==_9_10AM or time==_10_10AM or time==_1110AM or time==_1_40PM or time==_3_45PM or time==_1210PM)
verticalLine(_macroColor)
verticalLabel(_macroColor, "M.C.")
// DTCC
if(time==_8PM or time==_845PM)
verticalLine(_dtccColor)
verticalLabel(_dtccColor, "DTCC")
// London Macros
if(time==_4_03AM or time==_2_33AM)
verticalLine(_londonColor)
verticalLabel(_londonColor, "L.M.O")
if(time==_3AM or time==_4_30AM)
verticalLine(_londonColor)
verticalLabel(_londonColor, "L.M.C")
// Alert Any
if (time == _8_50AM)
alert("8:50a Macro Open Alert", alert.freq_once_per_bar_close)
if (time == _9_50AM)
alert("9:50a Macro Open Alert", alert.freq_once_per_bar_close)
if (time == _1_10PM)
alert("1:10p Macro Open Alert", alert.freq_once_per_bar_close)
if (time == _3_15PM)
alert("3:15p Macro Open Alert", alert.freq_once_per_bar_close)
if (time == _1150AM)
alert("11:50a Macro Open Alert", alert.freq_once_per_bar_close)
if (time == _1210PM)
alert("12:10a Macro Close Alert", alert.freq_once_per_bar_close)
if (time == _10_10AM)
alert("10:10a Macro Close Alert", alert.freq_once_per_bar_close)
if (time == _1110AM)
alert("11:10a Macro Close Alert", alert.freq_once_per_bar_close)
if (time == _1210PM)
alert("12:10a Macro Close Alert", alert.freq_once_per_bar_close)
if (time == _2_33AM)
alert("2:33a London Macro Open Alert", alert.freq_once_per_bar_close)
if (time == _3AM)
alert("3:00a London Macro Close Alert", alert.freq_once_per_bar_close)
if (time == _4_03AM)
alert("4:03a London Macro Open Alert", alert.freq_once_per_bar_close)
if (time == _4_30AM)
alert("4:30a London Macro Close Alert", alert.freq_once_per_bar_close)
if (time == _9_10AM)
alert("9:10a Macro Close Alert", alert.freq_once_per_bar_close)
if (time == _8PM)
alert("DTCC Open Alert", alert.freq_once_per_bar_close)
if (time == _845PM)
alert("DTCC Close Alert", alert.freq_once_per_bar_close)
// 2 min warning
if (time == _8_47AM)
alert("8:50a Macro Open in 2 Minutes", alert.freq_once_per_bar_close)
if (time == _9_47AM)
alert("9:50a Macro Open in 2 Minutes", alert.freq_once_per_bar_close)
if (time == _1_07PM)
alert("1:10p Macro Open in 2 Minutes", alert.freq_once_per_bar_close)
if (time == _3_12PM)
alert("3:15p Macro Open in 2 Minutes", alert.freq_once_per_bar_close)
if (time == _11_47AM)
alert("11:50a Macro Open in 2 Minutes", alert.freq_once_per_bar_close)
if (time == _12_07PM)
alert("12:10a Macro Close in 2 Minutes", alert.freq_once_per_bar_close)
if (time == _10_07AM)
alert("10:10a Macro Close in 2 Minutes", alert.freq_once_per_bar_close)
if (time == _11_07AM)
alert("11:10a Macro Close in 2 Minutes", alert.freq_once_per_bar_close)
if (time == _12_07PM)
alert("12:10a Macro Close in 2 Minutes", alert.freq_once_per_bar_close)
if (time == _2_30AM)
alert("2:33a London Macro Open in 2 Minutes", alert.freq_once_per_bar_close)
if (time == _2_57AM)
alert("3:00a London Macro Close in 2 Minutes", alert.freq_once_per_bar_close)
if (time == _4_00AM)
alert("4:03a London Macro Open in 2 Minutes", alert.freq_once_per_bar_close)
if (time == _4_27AM)
alert("4:30a London Macro Close in 2 Minutes", alert.freq_once_per_bar_close)
if (time == _9_07AM)
alert("9:10a Macro Close in 2 Minutes", alert.freq_once_per_bar_close)
if (time == _7_57PM)
alert("DTCC Open in 2 Minutes", alert.freq_once_per_bar_close)
if (time == _8_42PM)
alert("DTCC Close in 2 Minutes", alert.freq_once_per_bar_close)
// Alert
alertcondition(time == _8_50AM, title="8:50a Macro Open Alert", message="8:50AM Macro Open")
alertcondition(time == _9_50AM, title="9:50a Macro Open Alert", message="9:50AM Macro Open")
alertcondition(time == _1050AM, title="10:50a Macro Open Alert", message="10:50AM Macro Open")
alertcondition(time == _1_10PM, title="1:10p Macro Open Alert", message="1:10PM Macro Open")
alertcondition(time == _1_40PM, title="1:40p Macro Close Alert", message="1:40PM Macro Close")
alertcondition(time == _3_15PM, title="3:15p Macro Open Alert", message="3:15PM Macro Open")
alertcondition(time == _9_10AM, title="9:10a Macro Close Alert", message="9:10AM Macro Close")
alertcondition(time == _10_10AM, title="10:10a Macro Close Alert", message="10:10AM Macro Close")
alertcondition(time == _1110AM, title="11:10a Macro Close Alert", message="11:10AM Macro Close")
alertcondition(time == _1210PM, title="12:10p Macro Close Alert", message="12:10PM Macro Close")
alertcondition(time == _1150AM, title="11:50a Macro Open Alert", message="11:50AM Macro Open")
alertcondition(time == _2_33AM, title="2:33a London Macro Open Alert", message="2:33AM London Macro Open")
alertcondition(time == _4_03AM, title="4:03a London Macro Open Alert", message="4:03AM London Macro Open")
alertcondition(time == _3AM, title="3:00a London Macro Close Alert", message="3:00AM London Macro Close")
alertcondition(time == _4_30AM, title="4:30a London Macro Close Alert", message="4:30AM London Macro Close")
//alertcondition(time == _9PM, title="DTCC Open Alert", message="DTCC Open")
//alertcondition(time == _945PM, title="DTCC Close Alert", message="DTCC Close")
|
Central Bank Dark Energy Tracer | https://www.tradingview.com/script/ZWFyMLe7-Central-Bank-Dark-Energy-Tracer/ | DarklyEnergized | https://www.tradingview.com/u/DarklyEnergized/ | 241 | 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/
// © kstrat2001
//@version=5
// Central Bank Dark Energy Tracer
indicator(title="CBDE Tracer", shorttitle = "CBDET", overlay = true)
string[] symbol_preset_arr = array.from("QQQ", "SPX", "BTC", "ES1", "NQ1")
var factor_idx = 0
for i = 0 to (array.size(symbol_preset_arr) == 0 ? na : array.size(symbol_preset_arr) - 1)
if str.contains(syminfo.ticker, array.get(symbol_preset_arr, i))
factor_idx := i
float[] scale_factors_cbs = array.from(1.805, 18.0, 100.0, 18.0, 60)
float[] price_offsets_cbs = array.from(-289.0, -1950.0, 100.0, -1920.0, -7000)
float[] scale_factors_fred = array.from(0.0152, 0.14, 100.0, 0.14, 0.6)
float[] price_offsets_fred = array.from(-160, -215, 100.0, -185, -6000)
float[] scale_factors_rrp = array.from(0.705, 6.2, 100.0, 6.2, 30)
float[] price_offsets_rrp = array.from(92.0, 2245.0, 100.0, 2275.0, 3700)
// Scale factors without input settings
scale_factor_cbs = array.get(scale_factors_cbs, factor_idx)
price_offset_cbs = array.get(price_offsets_cbs, factor_idx)
scale_factor_fred = array.get(scale_factors_fred, factor_idx)
price_offset_fred = array.get(price_offsets_fred, factor_idx)
scale_factor_rrp = array.get(scale_factors_rrp, factor_idx)
price_offset_rrp = array.get(price_offsets_rrp, factor_idx)
//Comment the above definitions, and use these input defs instead to tweak the offset using input settings, rather than having to code them
// scale_factor_cbs = input.float(18, "Scale Factor", -10000.0, 10000.0, 0.001, inline = "cbs", group = "Non-US Central Bank Settings")
// price_offset_cbs = input.float(-1950, "Price Offset", -10000.0, 10000.0, 0.01, inline = "cbs", group = "Non-US Central Bank Settings")
// scale_factor_fred = input.float(0.11,"Scale Factor", -10000.0, 10000.0, 0.001, inline = "fed", group = "US Central Bank Settings")
// price_offset_fred = input.float(2080, "Pricce Offset", -10000.0, 10000.0, 5, inline = "fed", group = "US Central Bank Settings")
// scale_factor_rrp = input.float(6.2,"Scale Factor", -10000.0, 10000.0, 0.001, inline = "rrp", group = "RRP")
// price_offset_rrp = input.float(2245, "Pricce Offset", -10000.0, 10000.0, 5, inline = "rrp", group = "RRP")
//---------------------------------------------------------------------------------------------------------------
scale_factor_avg = input.float(1.0, "Scale Factor", -10000.0, 10000.0, 0.1, inline = "avg", group = "CBDET Signal Settings")
price_offset_avg = input.float(0, "Price Offset", -100000, 100000, 5, inline = "avg", group = "CBDET Signal Settings")
cbdet_avg_use_ema = input.bool(false, "Use EMA", "Draw CBDET signal with EMA to smooth out price signal", inline = "EMA Line", group = "CBDET Signal Settings")
cbdet_avg_ema_length = input.int(12, " with length:", 1, 1000, inline = "EMA Line", group = "CBDET Signal Settings")
cbdet_sma_length = input.int(200, " SMA length:", tooltip = "simple moving average using current chart time frame", minval = 1, maxval = 1000, inline = "SMA Line", group = "CBDET Signal Settings")
chart_settings_group_name = "Chart Settings"
show_divergence_bg_color_indicator = input.bool(false, "Price Divergence Indicator", group = chart_settings_group_name)
price_higher_bg_color = input.color(color.red, "Price Higher BG Color", group = chart_settings_group_name)
price_lower_bg_color = input.color(color.green, "Price Lower BG Color", group = chart_settings_group_name)
fed_bal_sheet_group_name = "Include Fed Balance Sheet Items"
include_wshoicl = input.bool(true, "Inflation Compensation (WSHOICL)", "Include Fed 'Inflation Compensation' (WSHOICL) from assets portion of balance sheet", group = fed_bal_sheet_group_name)
include_wupsho = input.bool(true, "Unamortized Premiums (WUPSHO)", "Include Fed 'Unamortized Premiums' (WUPSHO) from assets portion of balance sheet", group = fed_bal_sheet_group_name)
include_wlcfll = input.bool(true, "Loans (WLCFLL)", "Include Fed 'Loans' (WLCFLL) from assets portion of balance sheet", group = fed_bal_sheet_group_name)
include_wlad = input.bool(true, "Other/Remittances (WLAD)", "Include Fed remittances (WLAD) from liabilities portion of balance sheet", group = fed_bal_sheet_group_name)
tga_override = input.bool(false, "TGA Balance Override (Billions)", "Overrides the current balance of the Treasury General Accout. This allows use of the daily balance data rather than waiting for the weekly data to update.", inline = "tga_override", group = fed_bal_sheet_group_name)
tga_override_value = input.float(0, "", 0, 10000000000, 1, inline = "tga_override", group = fed_bal_sheet_group_name)
table_settings_str = "Table Settings"
show_info_table = input.bool(false, "Show Liquidity Table", group = table_settings_str)
show_fred_table = input.bool(false, "Show FRED Table", group = table_settings_str)
show_assets_table = input.bool(false, "Show CB Assets Table", group = table_settings_str)
// FOREIGN CENTRAL BANK ASSETS
currency_japan = request.security("FRED:JPNASSETS", "D", close)
currency_china = request.security("CNCBBS ", "D", close)
currency_uk = request.security("GBCBBS ", "W", close)
currency_ecb = request.security("ECBASSETSW ", "D", close)
currency_snb = request.security("CHCBBS ", "D", close)
currency_krw = request.security("ECONOMICS:KRCBBS", "D", close)
currency_cad = request.security("CACBBS", "D", close)
// FOREIGN CENTRAL BANK ASSETS
line_japan = request.security("FRED:JPNASSETS * FX_IDC:JPYUSD", "D", close, currency = currency.USD)
line_china = request.security("CNCBBS * FX_IDC:CNYUSD", "D", close, currency = currency.USD)
line_uk = request.security("GBCBBS * FX:GBPUSD", "D", close, currency = currency.USD)
line_ecb = request.security("ECBASSETSW * FX:EURUSD", "D", close, currency = currency.USD)
line_snb = request.security("CHCBBS", "D", close, currency = currency.USD)
line_krc = request.security("ECONOMICS:KRCBBS*FX_IDC:KRWUSD", "D", close, currency = currency.USD)
line_cad = request.security("CACBBS * CADUSD", "D", close, currency = currency.USD)
line_fed_walcl = request.security("FRED:WALCL", "D", close, currency = currency.USD)
line_fed_tga = request.security("WDTGAL", "D", close, currency = currency.USD)
line_wresbal = request.security("FRED:WRESBAL", "D", close, currency = currency.USD)
line_rrp = request.security("RRPONTSYD", "D", close, currency = currency.USD)
// Optional factors on Fed balance sheet
line_fed_wshoicl = request.security("WSHOICL", "D", close, currency = currency.USD)
line_fed_wupsho = request.security("WUPSHO", "D", close, currency = currency.USD)
line_fed_wlcfll = request.security("WLCFLL", "D", close, currency = currency.USD)
line_fed_wlad = request.security("WLAD", "D", close, currency = currency.USD)
// HELPER METHODS ------------------------------------------------------------------------
billions_str(value, currency_symbol = '$') =>
str.format("{0}{1, number, #,###.#} B",currency_symbol, value/1000000000)
oscillator_gradient_color(signal, high_color, low_color) =>
signal_max = ta.max(signal)
signal_min = ta.min(signal)
bull_color = color.from_gradient(signal, 0, signal_max, color.new(high_color, 90), color.new(high_color, 20))
bear_color = color.from_gradient(signal, signal_min, 0, color.new(low_color, 20), color.new(low_color, 90))
osc_color = signal < 0 ? bear_color : bull_color
// Currencies
cb_asstes = line_japan + line_china + line_uk + line_ecb + line_snb + line_krc + line_cad
cb_scaled = ((cb_asstes / 70000000000) * scale_factor_cbs) + price_offset_cbs
// Plot the raw signal for all non-US CB assets in USD
plot(cb_asstes/(1000*1000*1000), "Non-US Liquidity in Blns USD", color.olive, 1, trackprice = true, display = display.none)
// Plot the scaled version of non-UDS assets
plot(cb_scaled, "Non-US Liquidity (scaled)", color.white, 1, trackprice = true, display = display.none)
// FRED
// FED optional assets lines
wshoicl_final = (include_wshoicl ? 0 : line_fed_wshoicl)
wupsho_final = (include_wupsho ? 0 : line_fed_wupsho)
wlcfll_final = (include_wlcfll ? 0 : line_fed_wlcfll)
assets_subtractions = wlcfll_final + wupsho_final + wshoicl_final
assets_total = line_fed_walcl - assets_subtractions
// FED liabilities
tga_final = barstate.islast and tga_override ? tga_override_value * 1000000000 : line_fed_tga
wlad_final = (include_wlad ? line_fed_wlad : 0)
liabilities_total = tga_final + line_rrp + wlad_final
mid_wb_fred = assets_total - liabilities_total
fred_scaled = (mid_wb_fred / 200000000) * scale_factor_fred + price_offset_fred
plot(fred_scaled, "US Fed Liquidity (scaled)", color.lime, 1, trackprice = true, display = display.none)
rrp_scaled = (1/line_rrp * 2000000000000 * 307) * scale_factor_rrp + price_offset_rrp
plot(rrp_scaled, "Reverse Repo Liquidity (scaled)", color.orange, 1, trackprice = true, display = display.none)
aggregate_signal = ((fred_scaled + cb_scaled) * 0.5 * scale_factor_avg) + price_offset_avg
aggregate_signal_ema = ta.ema(aggregate_signal, cbdet_avg_ema_length)
plot(cbdet_avg_use_ema ? aggregate_signal_ema : aggregate_signal, "Combined CBDET Formula", color.purple, linewidth = 2, trackprice = true)
// DMA signal
aggregate_signal_sma = ta.sma(aggregate_signal, cbdet_sma_length)
plot(aggregate_signal_sma, "CBDET SMA", color.rgb(5, 203, 243), linewidth = 1, trackprice = false, display = display.none)
bg_color = chart.bg_color
divergence_signal = close - (cbdet_avg_use_ema ? aggregate_signal_ema : aggregate_signal)
if(show_divergence_bg_color_indicator)
//bg_color := (aggregate_signal < close) ? price_higher_bg_color : price_lower_bg_color
bg_color := oscillator_gradient_color(divergence_signal, price_higher_bg_color, price_lower_bg_color)
bgcolor(bg_color, display = show_divergence_bg_color_indicator ? display.all : display.none)
create_info_column(table, col, usd_signal, color_positive, color_negative, label_str, inverted) =>
delta = (usd_signal[0] - usd_signal[1]) * (inverted ? -1.0 : 1.0)
table.cell(table, col, 0, label_str, bgcolor = color.white)
table.cell(table, col, 1, billions_str(usd_signal[0]), bgcolor = color.white)
table.cell(table, col, 2, billions_str(delta), bgcolor = delta > 0 ? color.green : color.orange)
// Draw info table
if show_info_table
num_cols = 10
num_rows = 3
var table info_table = table.new(position.bottom_right, num_cols, num_rows, frame_color = color.gray, bgcolor = color.gray, border_width = 1, frame_width = 1, border_color = color.black)
// Header
table.cell(info_table, 0, 1, "Total", bgcolor = color.white)
table.cell(info_table, 0, 2, "1 bar delta", bgcolor = color.white)
create_info_column(info_table, 1, line_japan, color.green, color.orange, "JPY Assets", false)
create_info_column(info_table, 2, line_china, color.green, color.orange, "CNY Assets", false)
create_info_column(info_table, 3, line_uk, color.green, color.orange, "UK Assets", false)
create_info_column(info_table, 4, line_ecb, color.green, color.orange, "ECB Assets", false)
create_info_column(info_table, 5, line_snb, color.green, color.orange, "SNB Assets", false)
create_info_column(info_table, 6, line_krc, color.green, color.orange, "KRC Assets", false)
create_info_column(info_table, 7, line_cad, color.green, color.orange, "CAD Assets", false)
create_info_column(info_table, 8, cb_asstes, color.green, color.orange, "Non-US Total", false)
create_info_column(info_table, 9, mid_wb_fred, color.green, color.orange, "FRED Formula", false)
// Draw info table
if show_fred_table
num_cols = 5
num_rows = 3
var table fred_table = table.new(position.bottom_left, num_cols, num_rows, frame_color = color.gray, bgcolor = color.gray, border_width = 1, frame_width = 1, border_color = color.black)
// Header
table.cell(fred_table, 0, 1, "Total", bgcolor = color.white)
table.cell(fred_table, 0, 2, "1 bar delta", bgcolor = color.white)
create_info_column(fred_table, 1, line_rrp, color.green, color.orange, "FRED RRP", true)
create_info_column(fred_table, 2, line_wresbal, color.green, color.orange, "WRESBAL", false)
create_info_column(fred_table, 3, line_fed_tga, color.green, color.orange, "FRED TGA", true)
create_info_column(fred_table, 4, line_fed_walcl, color.green, color.orange, "FRED WALCL", false)
create_currency_info_column(table, col, currency_signal, color_positive, color_negative, label_str, currency_symbol = '$') =>
delta = (currency_signal[0] - currency_signal[1])
table.cell(table, col, 0, label_str, bgcolor = color.white)
table.cell(table, col, 1, billions_str(currency_signal[0], currency_symbol), bgcolor = color.white)
table.cell(table, col, 2, billions_str(delta, currency_symbol), bgcolor = delta > 0 ? color.green : color.orange)
// Render currency table
if show_assets_table
num_cols = 8
num_rows = 3
var table info_table = table.new(position.top_right, num_cols, num_rows, frame_color = color.gray, bgcolor = color.gray, border_width = 1, frame_width = 1, border_color = color.black)
// Header
table.cell(info_table, 0, 1, "Total", bgcolor = color.white)
table.cell(info_table, 0, 2, "1 bar chng", bgcolor = color.white)
create_currency_info_column(info_table, 1, currency_japan, color.green, color.orange, "JPY", currency_symbol = "¥")
create_currency_info_column(info_table, 2, currency_china, color.green, color.orange, "CNY", currency_symbol = "¥")
create_currency_info_column(info_table, 3, currency_uk, color.green, color.orange, "GBP", currency_symbol = "£")
create_currency_info_column(info_table, 4, currency_ecb, color.green, color.orange, "Euro", currency_symbol = "€")
create_currency_info_column(info_table, 5, currency_snb, color.green, color.orange, "SNB", currency_symbol = "$")
create_currency_info_column(info_table, 6, currency_krw, color.green, color.orange, "KRW", currency_symbol = "₩")
create_currency_info_column(info_table, 7, currency_cad, color.green, color.orange, "CAD", currency_symbol = "$")
|
Majors HOD/LOD | https://www.tradingview.com/script/71CK9jZK-Majors-HOD-LOD/ | Level8Trading | https://www.tradingview.com/u/Level8Trading/ | 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/
// © Level8Trading
//@version=5
indicator("Majors HOD/LOD", overlay = true)
show_labels = input.bool(false, title = "Show Labels")
timeSpan = time(timeframe.period, "0930-1600:1234567", "America/New_York")
timeStart = time(timeframe.period, "0930-0931:1234567", "America/New_York")
timeEnd = time(timeframe.period, "1559-1600:1234567", "America/New_York")
var float qqqHod = 0.0
var float qqqLod = 0.0
qqqHigh = request.security("NASDAQ:QQQ", timeframe.period, high)
qqqCurrent = request.security("NASDAQ:QQQ", timeframe.period, close)
qqqLow = request.security("NASDAQ:QQQ", timeframe.period, low)
var float xlfHod = 0.0
var float xlfLod = 0.0
xlfHigh = request.security("AMEX:XLF", timeframe.period, high)
xlfCurrent = request.security("AMEX:XLF", timeframe.period, close)
xlfLow = request.security("AMEX:XLF", timeframe.period, low)
var float xlvHod = 0.0
var float xlvLod = 0.0
xlvHigh = request.security("AMEX:XLV", timeframe.period, high)
xlvCurrent = request.security("AMEX:XLV", timeframe.period, close)
xlvLow = request.security("AMEX:XLV", timeframe.period, low)
if timeframe.isintraday
isNewDay = timeStart and not timeEnd
if isNewDay
qqqHod := qqqHigh
qqqLod := qqqLow
xlfHod := xlfHigh
xlfLod := xlfLow
xlvHod := xlvHigh
xlvLod := xlvLow
bool qqqAtHigh = qqqCurrent > qqqHod ? true : false
bool qqqAtLow = qqqCurrent < qqqLod ? true : false
qqqHod := qqqHigh > qqqHod ? qqqHigh : qqqHod
qqqLod := qqqLow < qqqLod ? qqqLow : qqqLod
bool xlfAtHigh = xlfCurrent > xlfHod ? true : false
bool xlfAtLow = xlfCurrent < xlfLod ? true : false
xlfHod := xlfHigh > xlfHod ? xlfHigh : xlfHod
xlfLod := xlfLow < xlfLod ? xlfLow : xlfLod
bool xlvAtHigh = xlvCurrent > xlvHod ? true : false
bool xlvAtLow = xlvCurrent < xlvLod ? true : false
xlvHod := xlvHigh > xlvHod ? xlvHigh : xlvHod
xlvLod := xlvLow < xlvLod ? xlvLow : xlvLod
bool allAtHigh = false
if qqqAtHigh and xlfAtHigh and xlvAtHigh
if show_labels
label.new(bar_index, high, yloc = yloc.abovebar, size = size.tiny, color = color.new(color.teal, 50), style = label.style_label_down)
allAtHigh := true
bool allAtLow = false
if qqqAtLow and xlfAtLow and xlvAtLow
if show_labels
label.new(bar_index, low, yloc = yloc.belowbar, size = size.tiny, color = color.new(color.red, 50), style = label.style_label_up)
allAtLow := true
displayTable = table.new(position.top_right, 1, 2, bgcolor = color(na))
table.cell(displayTable, 0, 0, text = " ")
if barstate.islast
table.cell(displayTable, 0, 1, text = allAtHigh ? "Majors @ HOD 🡅" : allAtLow ? "Majors @ LOD 🡇" : "Mixed 🡅🡇", bgcolor = allAtHigh ? color.new(color.teal, 50) : allAtLow ? color.new(color.red, 50) : color.new(color.blue, 50), text_color = color.white)
if allAtHigh
alert("Majors @ HOD")
if allAtLow
alert("Majors @ LOD") |
Dynamo | https://www.tradingview.com/script/2v6xWp3g-Dynamo/ | sudoMode | https://www.tradingview.com/u/sudoMode/ | 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/
// © sudoMode
//@version=5
//@release=0.0.3
indicator(title = 'Multi-Strength Indicator', shorttitle = 'Dynamo', max_bars_back = 100)
// --- constants ---
// supported indices
VOLUME = 'Volume'
VOLUME_MA = 'Volume MA'
RSI = 'RSI'
RSI_MA = 'RSI MA'
STOCHASTIC = 'Stochastic'
STOCHASTIC_MA = 'Stochastic MA'
ADX = 'ADX'
DMI_P = 'DMI+'
DMI_N = 'DMI-'
// --- user input ---
// volume
volume_toggle = input.bool(true, title = 'Show Volume', inline = '1', group = VOLUME)
volume_ma_toggle = input.bool(false, title = 'Show MA', inline = '2', group = VOLUME)
volume_ma_length = input.int(14, title = 'Length', inline = '2', group = VOLUME)
// rsi
rsi_toggle = input.bool(true, title = 'Show RSI', inline = '3', group = RSI)
rsi_length = input.int(14, title = 'Length', inline = '3', group = RSI)
rsi_ma_length = input.int(3, title = 'Smoothening', inline = '3', group = RSI)
rsi_ma_toggle= input.bool(false, title = 'Show MA', inline = '4', group = RSI)
// stochastic
stoch_toggle = input.bool(true, title = 'Show Stochastic', inline = '5', group = STOCHASTIC)
stoch_length = input.int(14, title = 'Length', inline = '5', group = STOCHASTIC)
stoch_ma_length = input.int(3, title = 'Smoothening', inline = '5', group = STOCHASTIC)
stoch_ma_toggle = input.bool(false, title = 'Show MA', inline = '6', group = STOCHASTIC)
// adx
adx_toggle = input.bool(true, title = 'Show ADX', inline = '7', group = ADX)
adx_length = input.int(14, title = 'Length', inline = '7', group = ADX)
adx_ma_length = input.int(14, title = 'Smoothening', inline = '7', group = ADX)
dmi_toggle = input.bool(false, title = 'Show DMI', inline = '8', group = ADX)
// --- utils ---
// base model
type Index
float value = na
color _color = na
// view control switches
show_everything = volume_toggle and volume_ma_toggle and
rsi_toggle and rsi_ma_toggle and
stoch_toggle and stoch_ma_toggle and
adx_toggle and dmi_toggle
mute_volume = not show_everything and (rsi_ma_toggle or stoch_ma_toggle or dmi_toggle)
mute_volume_ma = rsi_ma_toggle or stoch_ma_toggle or dmi_toggle
show_volume = volume_toggle or show_everything
show_volume_ma = (volume_toggle and volume_ma_toggle) and not(mute_volume_ma)
mute_rsi = not show_everything and (volume_ma_toggle or stoch_ma_toggle or dmi_toggle)
mute_rsi_ma = volume_ma_toggle or stoch_ma_toggle or dmi_toggle
show_rsi = rsi_toggle or show_everything
show_rsi_ma = (rsi_toggle and rsi_ma_toggle) and not(mute_rsi_ma)
mute_stoch = not show_everything and (volume_ma_toggle or rsi_ma_toggle or dmi_toggle)
mute_stoch_ma = volume_ma_toggle or rsi_ma_toggle or dmi_toggle
show_stoch = stoch_toggle or show_everything
show_stoch_ma = (stoch_toggle and stoch_ma_toggle) and not(mute_stoch_ma)
mute_adx = not show_everything and (volume_ma_toggle or rsi_ma_toggle or stoch_ma_toggle)
mute_dmi = volume_ma_toggle or rsi_ma_toggle or stoch_ma_toggle
show_adx = adx_toggle or show_everything
show_dmi = (adx_toggle and dmi_toggle) and not(mute_dmi)
// dynamic color generation
color_engine(component) =>
switch component
VOLUME => show_volume ? color.new(color.purple, mute_volume ? 70 : 0) : na
VOLUME_MA => volume_ma_toggle ? color.new(color.lime, show_volume_ma ? 0 : mute_volume_ma ? 70 : 100) : na
RSI => show_rsi ? color.new(color.aqua, mute_rsi ? 70 : 0) : na
RSI_MA => rsi_ma_toggle ? color.new(color.blue, show_rsi_ma ? 0 : mute_rsi_ma ? 70 : 100) : na
STOCHASTIC => show_stoch ? color.new(color.gray, mute_stoch ? 70 : 40) : na
STOCHASTIC_MA => stoch_ma_toggle ? color.new(color.yellow, show_stoch_ma ? 0 : mute_stoch_ma ? 70 : 100) : na
ADX => show_adx ? color.new(color.orange, mute_adx ? 70 : 0) : na
DMI_P => dmi_toggle ? color.new(color.green, show_dmi ? 0 : mute_dmi ? 70 : 100) : na
DMI_N => dmi_toggle ? color.new(color.red, show_dmi ? 0 : mute_dmi ? 70 : 100) : na
// return volume or volume ma
get_volume_component(component = 'Volume') =>
min = ta.min(volume)
max = ta.max(volume)
_range = max - min
_volume = ((volume - min) / _range) * 100
switch component
VOLUME => Index.new(_volume, color_engine(component))
VOLUME_MA => Index.new(ta.sma(_volume, volume_ma_length), color_engine(component))
// return rsi or rsi ma
get_rsi_component(length, smoothening, _close, component = 'RSI') =>
switch component
RSI => Index.new(ta.ema(ta.rsi(_close, length), smoothening), color_engine(component))
RSI_MA => Index.new(ta.sma(ta.ema(ta.rsi(_close, length), smoothening), length), color_engine(component))
// return stochastic or stochastic ma
get_stochastic_component(length, smoothening, _close, _high, _low, component = 'Stochastic') =>
switch component
STOCHASTIC => Index.new(ta.sma(ta.stoch(_close, _high, _low, length), smoothening), color_engine(component))
STOCHASTIC_MA => Index.new(ta.sma(ta.sma(ta.stoch(_close, _high, _low, length), smoothening), length), color_engine(component))
// return adx or dmi+/dmi-
get_adx_component(length, smoothening, component = 'ADX') =>
[dmi_positive, dmi_negative, adx] = ta.dmi(length, smoothening)
switch component
ADX => Index.new(adx, color_engine(component))
DMI_P => Index.new(dmi_positive, color_engine(component))
DMI_N => Index.new(dmi_negative, color_engine(component))
// each index has a dedicated worker
index_factory(index) =>
switch index
VOLUME => get_volume_component(component = index)
VOLUME_MA => get_volume_component(component = index)
RSI => get_rsi_component(rsi_length, rsi_ma_length, close, component = index)
RSI_MA => get_rsi_component(rsi_length, rsi_ma_length, close, component = index)
STOCHASTIC => get_stochastic_component(stoch_length, stoch_ma_length, close, high, low, component = index)
STOCHASTIC_MA => get_stochastic_component(stoch_length, stoch_ma_length, close, high, low, component = index)
ADX => get_adx_component(adx_length, adx_ma_length, component = index)
DMI_P => get_adx_component(adx_length, adx_ma_length, component = index)
DMI_N => get_adx_component(adx_length, adx_ma_length, component = index)
=> Index.new() // generate an empty instance on invalid input
// --- driver ---
// --- plots ---
// draw background lines
__hline = color.rgb(66, 66, 66, 66)
top = hline(75, title = 'Top Line', color = __hline, linewidth = 2)
bottom = hline(25, title = 'Bottom Line', color = __hline, linewidth = 2)
middle = hline(50, title = 'Middle Line', color = __hline)
// draw indices
_volume = index_factory(VOLUME)
plot(_volume.value, title = VOLUME, color = _volume._color, style = plot.style_columns)
volume_ma = index_factory(VOLUME_MA)
plot(volume_ma.value, title = VOLUME_MA, color = volume_ma._color)
rsi = index_factory(RSI)
plot(rsi.value, title = RSI, color = rsi._color, linewidth = 2)
rsi_ma = index_factory(RSI_MA)
plot(rsi_ma.value, title = RSI_MA, color = rsi_ma._color, linewidth = 1)
stoch = index_factory(STOCHASTIC)
plot(stoch.value, title = STOCHASTIC, color = stoch._color, style = plot.style_histogram)
stoch_ma = index_factory(STOCHASTIC_MA)
plot(stoch_ma.value, title = STOCHASTIC_MA, color = stoch_ma._color)
adx = index_factory(ADX)
plot(adx.value, title = ADX, color = adx._color, linewidth = 2)
dmip = index_factory(DMI_P)
plot(dmip.value, title = DMI_P, color = dmip._color)
dmin = index_factory(DMI_N)
plot(dmin.value, title = DMI_N, color = dmin._color)
|
Bitcoin Correlation Map | https://www.tradingview.com/script/74E9YRKI-Bitcoin-Correlation-Map/ | Milvetti | https://www.tradingview.com/u/Milvetti/ | 143 | 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/
// © Milvetti
//@version=5
indicator("Bitcoin Correlation Map")
g1= "Settings"
g2="Reference Settings"
g3="Symbol Settings"
size = input.string("Normal","Size",options = ["Small","Normal","Large"],group = g1)
len= input.int(20,"Mov Lenght",group = g1)
cLen = input.int(200,"Correlation Lenght",minval = 1,maxval = 4999,group = g1)
base = input.symbol("BINANCE:BTCUSDT","Referenece Symbol",group = g2)
symbol1 = input.symbol("BINANCE:ETHUSDT",group = g3)
symbol2 = input.symbol("BINANCE:BNBUSDT",group = g3)
symbol3 = input.symbol("BINANCE:DOTUSDT",group = g3)
symbol4 = input.symbol("BINANCE:LTCUSDT",group = g3)
symbol5 = input.symbol("BINANCE:AVAXUSDT",group = g3)
symbol6 = input.symbol("BINANCE:SANDUSDT",group = g3)
symbol7 = input.symbol("BINANCE:ALGOUSDT",group = g3)
symbol8 = input.symbol("BINANCE:GALAUSDT",group = g3)
symbol9 = input.symbol("BINANCE:MANAUSDT",group = g3)
symbol10 = input.symbol("BINANCE:SOLUSDT",group = g3)
symbol11 = input.symbol("BINANCE:MATICUSDT",group = g3)
symbol12 = input.symbol("BINANCE:TRXUSDT",group = g3)
symbol13 = input.symbol("BINANCE:XMRUSDT",group = g3)
symbol14 = input.symbol("BINANCE:XRPUSDT",group = g3)
symbol15 = input.symbol("BINANCE:FTMUSDT",group = g3)
symbol16 = input.symbol("BINANCE:NEARUSDT",group = g3)
symbol17 = input.symbol("BINANCE:ENJUSDT",group = g3)
symbol18 = input.symbol("BINANCE:ATOMUSDT",group = g3)
symbol19 = input.symbol("BINANCE:ADAUSDT",group = g3)
symbol20 = input.symbol("BINANCE:COMPUSDT",group = g3)
symbol21 = input.symbol("BINANCE:ALICEUSDT",group = g3)
symbol22 = input.symbol("BINANCE:AAVEUSDT",group = g3)
symbol23 = input.symbol("BINANCE:CHZUSDT",group = g3)
symbol24 = input.symbol("BINANCE:CAKEUSDT",group = g3)
symbol25 = input.symbol("BINANCE:AXSUSDT",group = g3)
symbol26 = input.symbol("BINANCE:BATUSDT",group = g3)
symbol27 = input.symbol("BINANCE:MKRUSDT",group = g3)
symbol28 = input.symbol("BINANCE:BCHUSDT",group = g3)
symbol29 = input.symbol("BINANCE:ICPUSDT",group = g3)
symbol30 = input.symbol("BINANCE:SOLUSDT",group = g3)
symbol31 = input.symbol("BINANCE:CRVUSDT",group = g3)
symbol32 = input.symbol("BINANCE:LRCUSDT",group = g3)
symbol33 = input.symbol("BINANCE:DOGEUSDT",group = g3)
symbol34 = input.symbol("BINANCE:SHIBUSDT",group = g3)
symbol35 = input.symbol("BINANCE:LINKUSDT",group = g3)
symbol36 = input.symbol("TVC:DXY",group = g3)
tableSize= switch size
"Small" => size.small
"Normal" => size.normal
"Large" => size.large
cor(x)=>
if bar_index<x and bar_index>0
bar_index
else
x
baseC = request.security(base,"",close)
c1 =math.round(ta.wma(ta.correlation(baseC, request.security(symbol1,"",close), len),cor(cLen)),2)
c2 =math.round(ta.wma(ta.correlation(baseC, request.security(symbol2,"",close), len),cor(cLen)),2)
c3 =math.round(ta.wma(ta.correlation(baseC, request.security(symbol3,"",close), len),cor(cLen)),2)
c4 =math.round(ta.wma(ta.correlation(baseC, request.security(symbol4,"",close), len),cor(cLen)),2)
c5 =math.round(ta.wma(ta.correlation(baseC, request.security(symbol5,"",close), len),cor(cLen)),2)
c6 =math.round(ta.wma(ta.correlation(baseC, request.security(symbol6,"",close), len),cor(cLen)),2)
c7 =math.round(ta.wma(ta.correlation(baseC, request.security(symbol7,"",close), len),cor(cLen)),2)
c8 =math.round(ta.wma(ta.correlation(baseC, request.security(symbol8,"",close), len),cor(cLen)),2)
c9 =math.round(ta.wma(ta.correlation(baseC, request.security(symbol9,"",close), len),cor(cLen)),2)
c10 =math.round(ta.wma(ta.correlation(baseC, request.security(symbol10,"",close), len),cor(cLen)),2)
c11 =math.round(ta.wma(ta.correlation(baseC, request.security(symbol11,"",close), len),cor(cLen)),2)
c12 =math.round(ta.wma(ta.correlation(baseC, request.security(symbol12,"",close), len),cor(cLen)),2)
c13 =math.round(ta.wma(ta.correlation(baseC, request.security(symbol13,"",close), len),cor(cLen)),2)
c14 =math.round(ta.wma(ta.correlation(baseC, request.security(symbol14,"",close), len),cor(cLen)),2)
c15 =math.round(ta.wma(ta.correlation(baseC, request.security(symbol15,"",close), len),cor(cLen)),2)
c16 =math.round(ta.wma(ta.correlation(baseC, request.security(symbol16,"",close), len),cor(cLen)),2)
c17 =math.round(ta.wma(ta.correlation(baseC, request.security(symbol17,"",close), len),cor(cLen)),2)
c18 =math.round(ta.wma(ta.correlation(baseC, request.security(symbol18,"",close), len),cor(cLen)),2)
c19 =math.round(ta.wma(ta.correlation(baseC, request.security(symbol19,"",close), len),cor(cLen)),2)
c20 =math.round(ta.wma(ta.correlation(baseC, request.security(symbol20,"",close), len),cor(cLen)),2)
c21=math.round(ta.wma(ta.correlation(baseC, request.security(symbol21,"",close), len),cor(cLen)),2)
c22 =math.round(ta.wma(ta.correlation(baseC, request.security(symbol22,"",close), len),cor(cLen)),2)
c23 =math.round(ta.wma(ta.correlation(baseC, request.security(symbol23,"",close), len),cor(cLen)),2)
c24 =math.round(ta.wma(ta.correlation(baseC, request.security(symbol24,"",close), len),cor(cLen)),2)
c25 =math.round(ta.wma(ta.correlation(baseC, request.security(symbol25,"",close), len),cor(cLen)),2)
c26 =math.round(ta.wma(ta.correlation(baseC, request.security(symbol26,"",close), len),cor(cLen)),2)
c27 =math.round(ta.wma(ta.correlation(baseC, request.security(symbol27,"",close), len),cor(cLen)),2)
c28 =math.round(ta.wma(ta.correlation(baseC, request.security(symbol28,"",close), len),cor(cLen)),2)
c29 =math.round(ta.wma(ta.correlation(baseC, request.security(symbol29,"",close), len),cor(cLen)),2)
c30=math.round(ta.wma(ta.correlation(baseC, request.security(symbol30,"",close), len),cor(cLen)),2)
c31=math.round(ta.wma(ta.correlation(baseC, request.security(symbol31,"",close), len),cor(cLen)),2)
c32=math.round(ta.wma(ta.correlation(baseC, request.security(symbol32,"",close), len),cor(cLen)),2)
c33=math.round(ta.wma(ta.correlation(baseC, request.security(symbol33,"",close), len),cor(cLen)),2)
c34=math.round(ta.wma(ta.correlation(baseC, request.security(symbol34,"",close), len),cor(cLen)),2)
c35=math.round(ta.wma(ta.correlation(baseC, request.security(symbol35,"",close), len),cor(cLen)),2)
c36=math.round(ta.wma(ta.correlation(baseC, request.security(symbol36,"",close), len),cor(cLen)),2)
headerColor = #131722
corColor = #fefcee
headerTextColor = color.white
textColor = color.white
corColor(x) =>
if x>0
color.new(color.green,10)
else
color.new(color.red,10)
var tablo=table.new(position=position.middle_center,columns=12,rows=6,bgcolor=headerColor ,frame_color=#151715, frame_width=2, border_width=2, border_color=color.new(color.black, 100) )
table.cell(tablo,0,0,syminfo.ticker(symbol1) ,text_color=headerTextColor,bgcolor = headerColor,text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,0,1,str.tostring(c1),text_color=textColor,bgcolor = corColor(c1),text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,0,2,syminfo.ticker(symbol2) ,text_color=headerTextColor,bgcolor = headerColor,text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,0,3,str.tostring(c2),text_color=textColor,bgcolor = corColor(c2),text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,0,4,syminfo.ticker(symbol3) ,text_color=headerTextColor,bgcolor = headerColor,text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,0,5,str.tostring(c3),text_color=textColor,bgcolor = corColor(c3),text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,1,0,syminfo.ticker(symbol4) ,text_color=headerTextColor,bgcolor = headerColor,text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,1,1,str.tostring(c4),text_color=textColor,bgcolor = corColor(c4),text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,1,2,syminfo.ticker(symbol5) ,text_color=headerTextColor,bgcolor = headerColor,text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,1,3,str.tostring(c5),text_color=textColor,bgcolor = corColor(c5),text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,1,4,syminfo.ticker(symbol6) ,text_color=headerTextColor,bgcolor = headerColor,text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,1,5,str.tostring(c6),text_color=textColor,bgcolor = corColor(c6),text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,2,0,syminfo.ticker(symbol7) ,text_color=headerTextColor,bgcolor = headerColor,text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,2,1,str.tostring(c7),text_color=textColor,bgcolor = corColor(c7),text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,2,2,syminfo.ticker(symbol8) ,text_color=headerTextColor,bgcolor = headerColor,text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,2,3,str.tostring(c8),text_color=textColor,bgcolor = corColor(c8),text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,2,4,syminfo.ticker(symbol9) ,text_color=headerTextColor,bgcolor = headerColor,text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,2,5,str.tostring(c9),text_color=textColor,bgcolor = corColor(c9),text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,3,0,syminfo.ticker(symbol10) ,text_color=headerTextColor,bgcolor = headerColor,text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,3,1,str.tostring(c10),text_color=textColor,bgcolor = corColor(c10),text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,3,2,syminfo.ticker(symbol11) ,text_color=headerTextColor,bgcolor = headerColor,text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,3,3,str.tostring(c11),text_color=textColor,bgcolor = corColor(c11),text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,3,4,syminfo.ticker(symbol12) ,text_color=headerTextColor,bgcolor = headerColor,text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,3,5,str.tostring(c12),text_color=textColor,bgcolor = corColor(c12),text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,4,0,syminfo.ticker(symbol13) ,text_color=headerTextColor,bgcolor = headerColor,text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,4,1,str.tostring(c13),text_color=textColor,bgcolor = corColor(c13),text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,4,2,syminfo.ticker(symbol14) ,text_color=headerTextColor,bgcolor = headerColor,text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,4,3,str.tostring(c14),text_color=textColor,bgcolor = corColor(c14),text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,4,4,syminfo.ticker(symbol15) ,text_color=headerTextColor,bgcolor = headerColor,text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,4,5,str.tostring(c15),text_color=textColor,bgcolor = corColor(c15),text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,5,0,syminfo.ticker(symbol16) ,text_color=headerTextColor,bgcolor = headerColor,text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,5,1,str.tostring(c16),text_color=textColor,bgcolor = corColor(c16),text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,5,2,syminfo.ticker(symbol17) ,text_color=headerTextColor,bgcolor = headerColor,text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,5,3,str.tostring(c17),text_color=textColor,bgcolor = corColor(c17),text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,5,4,syminfo.ticker(symbol18) ,text_color=headerTextColor,bgcolor = headerColor,text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,5,5,str.tostring(c18),text_color=textColor,bgcolor = corColor(c18),text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,6,0,syminfo.ticker(symbol19) ,text_color=headerTextColor,bgcolor = headerColor,text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,6,1,str.tostring(c19),text_color=textColor,bgcolor = corColor(c19),text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,6,2,syminfo.ticker(symbol20) ,text_color=headerTextColor,bgcolor = headerColor,text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,6,3,str.tostring(c20),text_color=textColor,bgcolor = corColor(c20),text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,6,4,syminfo.ticker(symbol21) ,text_color=headerTextColor,bgcolor = headerColor,text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,6,5,str.tostring(c21),text_color=textColor,bgcolor = corColor(c21),text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,7,0,syminfo.ticker(symbol22) ,text_color=headerTextColor,bgcolor = headerColor,text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,7,1,str.tostring(c22),text_color=textColor,bgcolor = corColor(c22),text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,7,2,syminfo.ticker(symbol23) ,text_color=headerTextColor,bgcolor = headerColor,text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,7,3,str.tostring(c23),text_color=textColor,bgcolor = corColor(c23),text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,7,4,syminfo.ticker(symbol24) ,text_color=headerTextColor,bgcolor = headerColor,text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,7,5,str.tostring(c24),text_color=textColor,bgcolor = corColor(c24),text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,8,0,syminfo.ticker(symbol25) ,text_color=headerTextColor,bgcolor = headerColor,text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,8,1,str.tostring(c25),text_color=textColor,bgcolor = corColor(c25),text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,8,2,syminfo.ticker(symbol26) ,text_color=headerTextColor,bgcolor = headerColor,text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,8,3,str.tostring(c26),text_color=textColor,bgcolor = corColor(c26),text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,8,4,syminfo.ticker(symbol27) ,text_color=headerTextColor,bgcolor = headerColor,text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,8,5,str.tostring(c27),text_color=textColor,bgcolor = corColor(c27),text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,9,0,syminfo.ticker(symbol28) ,text_color=headerTextColor,bgcolor = headerColor,text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,9,1,str.tostring(c28),text_color=textColor,bgcolor = corColor(c28),text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,9,2,syminfo.ticker(symbol29) ,text_color=headerTextColor,bgcolor = headerColor,text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,9,3,str.tostring(c29),text_color=textColor,bgcolor = corColor(c29),text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,9,4,syminfo.ticker(symbol30) ,text_color=headerTextColor,bgcolor = headerColor,text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,9,5,str.tostring(c30),text_color=textColor,bgcolor = corColor(c30),text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,10,0,syminfo.ticker(symbol31) ,text_color=headerTextColor,bgcolor = headerColor,text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,10,1,str.tostring(c31),text_color=textColor,bgcolor = corColor(c31),text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,10,2,syminfo.ticker(symbol32) ,text_color=headerTextColor,bgcolor = headerColor,text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,10,3,str.tostring(c32),text_color=textColor,bgcolor = corColor(c32),text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,10,4,syminfo.ticker(symbol33) ,text_color=headerTextColor,bgcolor = headerColor,text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,10,5,str.tostring(c33),text_color=textColor,bgcolor = corColor(c33),text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,11,0,syminfo.ticker(symbol34) ,text_color=headerTextColor,bgcolor = headerColor,text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,11,1,str.tostring(c34),text_color=textColor,bgcolor = corColor(c34),text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,11,2,syminfo.ticker(symbol35) ,text_color=headerTextColor,bgcolor = headerColor,text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,11,3,str.tostring(c35),text_color=textColor,bgcolor = corColor(c35),text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,11,4,syminfo.ticker(symbol36) ,text_color=headerTextColor,bgcolor = headerColor,text_halign = text.align_center,text_size = tableSize)
table.cell(tablo,11,5,str.tostring(c36),text_color=textColor,bgcolor = corColor(c36),text_halign = text.align_center,text_size = tableSize)
|
Multiple Indicators Screener | https://www.tradingview.com/script/17jvDjJ9-Multiple-Indicators-Screener/ | cyroblazer | https://www.tradingview.com/u/cyroblazer/ | 292 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Multiple Indicator Screener for 40 FnO Contracts. https://in.tradingview.com/u/QuantNomad/ Base code from
//QuantNomad's Open Source Screener with multiple indicator.
// © cyroblazer
//@version=5
indicator('Multiple Screener with indicators(BB %B, RSI, ADX, Adapted RSI, TEMA, RSI Hidden/Regular[Cyro])',
shorttitle='Multiple Stocks Screener[cyro]',
overlay=true, max_bars_back=2000)
string T1 = 'Check this if you are using dark theme for better color visibility'
string T2 = 'Tiny font size recommended for mobile app or multiple layout'
bool DarkMode = input.bool(false, "Activate Dark Mode", T1, group="System", confirm=true)
bool MobileMode = input.bool(false, "Enable Mobile Mode", T2, group="System", confirm=true)
string i_s_Y = input.string('top',
'Table Position',
inline='1',
options=['top', 'middle', 'bottom'],
group="Table Styling")
string i_s_X = input.string('right',
'',
inline='1',
options=['left', 'center', 'right'],
group="Table Styling")
string i_s_font = input.string('small',
'Font size',
tooltip=T2,
options=['tiny', 'small', 'normal', 'large', 'huge'],
confirm=true,
group="Table Styling")
color _DarkTblClr = input(color.rgb(11, 3, 3),
"Dark Mode Table Color",
inline="",
group="Table Styling")
color _DarkTxtClr = input(color.rgb(255, 255, 255),
"Dark Mode Text Color",
inline="",
group="Table Styling")
color _DarkBulClr = input(color.rgb(111, 215, 58),
"Dark Mode Bull Color",
inline="",
group="Table Styling")
color _DarkBerClr = input(color.rgb(237, 82, 82),
"Dark Mode Bear Color",
inline="",
group="Table Styling")
color _LightTblClr = input(color.rgb(11, 3, 3),
"Light Mode Table Color",
inline="-",
group="Table Styling")
color _LightTxtClr = input(color.rgb(255, 255, 255),
"Light Mode Text Color",
inline="-",
group="Table Styling")
color _LightBulClr = input(color.rgb(35, 132, 30),
"Light Mode Bull Color",
inline="-",
group="Table Styling")
color _LightBerClr = input(color.rgb(225, 72, 72),
" Mode Bear Color",
inline="-",
group="Table Styling")
color _colTable = DarkMode ? _DarkTblClr : _LightTblClr
color _colText = DarkMode ? _DarkTxtClr : _LightTxtClr
color bullish_col = DarkMode ? _DarkBulClr : _LightBulClr
color bearish_col = DarkMode ? _DarkBerClr : _LightBerClr
//Adapted RSI
int _adaLen = input.int(defval=14, title='Adaptive RSI Length', group="Adaptive RSI")
float _adaSrc = input.source(defval=close, title="Adaptive RSI Source", group="Adaptive RSI")
// RSI Hidden and Regular Bullish Signal
//int lbR = input.int(title="Pivot Lookback Right", defval=5, group = " ")
//int lbL = input.int(title="Pivot Lookback Left", defval=5, group = " ")
//int rangeUpper = input.int(title="Max of Lookback Range", defval=60, group = " ")
//int rangeLower = input.int(title="Min of Lookback Range", defval=5, group = " ")
int _rsiLen = input.int(14, title = "RSI Length", group = " ")
int _obLevel = input.int(70, title = "RSI Overbought", group = " ")
int _osLevel = input.int(30, title = "RSI Oversold", group = " ")
//bool plotHidden = input.bool(true,title = 'Plot Hidden', group = " ")
//Bollinger Band %B
int _bbLength = input.int(defval = 20, title = "Bollinger Band Period", minval=1, group = "BB % B")
float _bbSrc = input.source(defval = close, title="Source", group = "BB % B")
float _bbMult = input.float(defval = 2.00, title="Stdev", minval=0.001, maxval=50,group = 'BB % B')
// ADX Params
int adx_smooth = input.int(14, title = "ADX Smoothing", group = 'ADX')
int adx_dilen = input.int(14, title = "ADX DI Length", group = 'ADX')
int adx_level = input.int(40, title = "ADX Level", group = 'ADX')
//EMA
int _Base = input.int(6, title = "Base Smoothing", group = "TEMA")
int _Sline = input.int(10, title = "Slow EMA Line", group = "TEMA")
int _Lline = input.int(14, title = "Fast EMA Line", group = "TEMA")
////////////////////////////////////////////////////////////////////////////
/////////////
// SYMBOLS //
u01 = input.bool(true, title = "", group = 'Symbols', inline = 's01')
u02 = input.bool(true, title = "", group = 'Symbols', inline = 's02')
u03 = input.bool(true, title = "", group = 'Symbols', inline = 's03')
u04 = input.bool(true, title = "", group = 'Symbols', inline = 's04')
u05 = input.bool(true, title = "", group = 'Symbols', inline = 's05')
u06 = input.bool(true, title = "", group = 'Symbols', inline = 's06')
u07 = input.bool(true, title = "", group = 'Symbols', inline = 's07')
u08 = input.bool(true, title = "", group = 'Symbols', inline = 's08')
u09 = input.bool(true, title = "", group = 'Symbols', inline = 's09')
u10 = input.bool(true, title = "", group = 'Symbols', inline = 's10')
u11 = input.bool(true, title = "", group = 'Symbols', inline = 's11')
u12 = input.bool(true, title = "", group = 'Symbols', inline = 's12')
u13 = input.bool(true, title = "", group = 'Symbols', inline = 's13')
u14 = input.bool(true, title = "", group = 'Symbols', inline = 's14')
u15 = input.bool(true, title = "", group = 'Symbols', inline = 's15')
u16 = input.bool(true, title = "", group = 'Symbols', inline = 's16')
u17 = input.bool(true, title = "", group = 'Symbols', inline = 's17')
u18 = input.bool(true, title = "", group = 'Symbols', inline = 's18')
u19 = input.bool(true, title = "", group = 'Symbols', inline = 's19')
u20 = input.bool(true, title = "", group = 'Symbols', inline = 's20')
u21 = input.bool(true, title = "", group = 'Symbols', inline = 's21')
u22 = input.bool(true, title = "", group = 'Symbols', inline = 's22')
u23 = input.bool(true, title = "", group = 'Symbols', inline = 's23')
u24 = input.bool(true, title = "", group = 'Symbols', inline = 's24')
u25 = input.bool(true, title = "", group = 'Symbols', inline = 's25')
u26 = input.bool(true, title = "", group = 'Symbols', inline = 's26')
u27 = input.bool(true, title = "", group = 'Symbols', inline = 's27')
u28 = input.bool(true, title = "", group = 'Symbols', inline = 's28')
u29 = input.bool(true, title = "", group = 'Symbols', inline = 's29')
u30 = input.bool(true, title = "", group = 'Symbols', inline = 's30')
u31 = input.bool(true, title = "", group = 'Symbols', inline = 's31')
u32 = input.bool(true, title = "", group = 'Symbols', inline = 's32')
u33 = input.bool(true, title = "", group = 'Symbols', inline = 's33')
u34 = input.bool(true, title = "", group = 'Symbols', inline = 's34')
u35 = input.bool(false, title = "", group = 'Symbols', inline = 's35')
u36 = input.bool(false, title = "", group = 'Symbols', inline = 's36')
u37 = input.bool(false, title = "", group = 'Symbols', inline = 's37')
u38 = input.bool(false, title = "", group = 'Symbols', inline = 's38')
u39 = input.bool(false, title = "", group = 'Symbols', inline = 's39')
u40 = input.bool(false, title = "", group = 'Symbols', inline = 's40')
s01 = input.symbol('TATACONSUM', group = 'Symbols', inline = 's01')
s02 = input.symbol('NIFTY', group = 'Symbols', inline = 's02')
s03 = input.symbol('BANKNIFTY', group = 'Symbols', inline = 's03')
s04 = input.symbol('TVSMOTOR', group = 'Symbols', inline = 's04')
s05 = input.symbol('AXISBANK', group = 'Symbols', inline = 's05')
s06 = input.symbol('TCS', group = 'Symbols', inline = 's06')
s07 = input.symbol('JINDALSTEL', group = 'Symbols', inline = 's07')
s08 = input.symbol('TATAMOTORs', group = 'Symbols', inline = 's08')
s09 = input.symbol('ADANIPORTS', group = 'Symbols', inline = 's09')
s10 = input.symbol('ACC', group = 'Symbols', inline = 's10')
s11 = input.symbol('SRF', group = 'Symbols', inline = 's11')
s12 = input.symbol('M_M', group = 'Symbols', inline = 's12')
s13 = input.symbol('ITC', group = 'Symbols', inline = 's13')
s14 = input.symbol('LUPIN', group = 'Symbols', inline = 's14')
s15 = input.symbol('AUROPHARMA', group = 'Symbols', inline = 's15')
s16 = input.symbol('HINDALCO', group = 'Symbols', inline = 's16')
s17 = input.symbol('TATASTEEL', group = 'Symbols', inline = 's17')
s18 = input.symbol('RELIANCE', group = 'Symbols', inline = 's18')
s19 = input.symbol('NTPC', group = 'Symbols', inline = 's19')
s20 = input.symbol('HAVELLS', group = 'Symbols', inline = 's20')
s21 = input.symbol('IPCALAB', group = 'Symbols', inline = 's21')
s22 = input.symbol('EICHERMOT', group = 'Symbols', inline = 's22')
s23 = input.symbol('AMBUJACEM', group = 'Symbols', inline = 's23')
s24 = input.symbol('NMDC', group = 'Symbols', inline = 's24')
s25 = input.symbol('ABFRL', group = 'Symbols', inline = 's25')
s26 = input.symbol('MANAPPURAM', group = 'Symbols', inline = 's26')
s27 = input.symbol('APOLLOTYRE', group = 'Symbols', inline = 's27')
s28 = input.symbol('ADANIENT', group = 'Symbols', inline = 's28')
s29 = input.symbol('BAJFINANCE', group = 'Symbols', inline = 's29')
s30 = input.symbol('INFY', group = 'Symbols', inline = 's30')
s31 = input.symbol('ASHOKLEY', group = 'Symbols', inline = 's31')
s32 = input.symbol('CANBK', group = 'Symbols', inline = 's32')
s33 = input.symbol('UPL', group = 'Symbols', inline = 's33')
s34 = input.symbol('SIEMENS', group = 'Symbols', inline = 's34')
s35 = input.symbol('PFC', group = 'Symbols', inline = 's35')
s36 = input.symbol('HCLTECH', group = 'Symbols', inline = 's36')
s37 = input.symbol('CIPLA', group = 'Symbols', inline = 's37')
s38 = input.symbol('TATACOMM', group = 'Symbols', inline = 's38')
s39 = input.symbol('MCX', group = 'Symbols', inline = 's39')
s40 = input.symbol('APOLLOHOSP', group = 'Symbols', inline = 's40')
//////////////////
// CALCULATIONS //
// Get only symbol
only_symbol(s) =>
array.get(str.split(s, ":"), 1)
//Uncomment this code for hidden Rsi
// Checking if Condition is true for how many bars
//_inRange(bool cond) =>
// bars = ta.barssince(cond == true)
// rangeLower <= bars and bars <= rangeUpper
// RSI function for normal and adapted RSI
rsi_func(int _rsiLen,float _adaSrc,simple int _adaLen) =>
float rsi = ta.rsi(_adaSrc,_adaLen)
alpharsi = 2 * math.abs(ta.rsi(_adaSrc, _adaLen) / 100 - 0.5)
float _arsi = 0.0
_arsi := math.round(alpharsi * _adaSrc + (1 - alpharsi) * nz(_arsi[1]),2)
[rsi,_arsi]
// ADX Function
dirmov(simple int len) =>
up = ta.change(high)
down = -ta.change(low)
plusDM = na(up) ? na : (up > down and up > 0 ? up : 0)
minusDM = na(down) ? na : (down > up and down > 0 ? down : 0)
truerange = ta.rma(ta.tr, len)
plus = fixnan(100 * ta.rma(plusDM, len) / truerange)
minus = fixnan(100 * ta.rma(minusDM, len) / truerange)
[plus, minus]
adx_func(simple int dilen, simple int adxlen) =>
[plus, minus] = dirmov(dilen)
sum = plus + minus
float adx = math.round(100 * ta.rma(math.abs(plus - minus) / (sum == 0 ? 1 : sum), adxlen),2)
// Function for Bollinger Bands %B
bb_func(float _bbSrc,simple int len) =>
basis = ta.sma(_bbSrc,_bbLength)
dev = _bbMult * ta.stdev(_bbSrc, _bbLength)
lower = basis - dev
upper = basis + dev
float bbr = math.round((_bbSrc - lower)/ (upper-lower), 2)
// Smooth TEMA function calculating cross over and under
tema_func(Smooth, ShortLine, LongLine) =>
Aema1 = ta.ema(close, Smooth)
Aema2 = ta.ema(Aema1, Smooth)
Aema3 = ta.ema(Aema2, Smooth)
Atema1 = 3 *(Aema1 - Aema2) + Aema3
Bema1 = ta.ema(close, Smooth)
Bema2 = ta.ema(Aema1, Smooth)
Bema3 = ta.ema(Aema2, Smooth)
Btema1 = 3 *(Aema1 - Aema2) + Aema3
short = ta.ema(Atema1, ShortLine)
long = ta.ema(Btema1, LongLine)
[short, long]
// Main Screener function
screener_func() =>
[temp_rsi, arsi] = rsi_func(_rsiLen,_adaSrc,_adaLen)
adx = adx_func(adx_dilen, adx_smooth)
bbr = bb_func(close, _bbLength)
[short,long] = tema_func(_Base, _Sline, _Lline)
_bullTema = ta.crossover(short,long)
_bearTema = ta.crossunder(short,long)
ematema = short > long ? "Up": long > short ? "Down" : _bullTema ? "Long" : _bearTema ? "Short" : 'Wait for Signal'
// RSI Divergence
//plFound = na(ta.pivotlow(temp_rsi, lbL, lbR)) ? false : true
//phFound = na(ta.pivothigh(temp_rsi, lbL, lbR)) ? false : true
// Regular Bullish
//rsiHL = temp_rsi[lbR] > ta.valuewhen(plFound, temp_rsi[lbR], 1) and _inRange(plFound[1])
//priceLL = low[lbR] < ta.valuewhen(plFound, low[lbR], 1)
// Hidden Bullish
//rsiLL = temp_rsi[lbR] < ta.valuewhen(plFound, temp_rsi[lbR], 1) and _inRange(plFound[1])
//priceHL = low[lbR] > ta.valuewhen(plFound, low[lbR], 1)
//_bull = (plotHidden and priceHL and rsiLL and plFound) ? 'Hidden Long Sig' :
//(priceLL and rsiHL and plFound) ? 'Regular Long Sig' : 'Wait for Trade'
// Regular Bearish
//rsiLH = temp_rsi[lbR] < ta.valuewhen(phFound, temp_rsi[lbR], 1) and _inRange(phFound[1])
//priceHH = high[lbR] > ta.valuewhen(phFound, high[lbR], 1)
// Hidden Bearish
//rsiHH = temp_rsi[lbR] > ta.valuewhen(phFound, temp_rsi[lbR], 1) and _inRange(phFound[1])
//priceLH = high[lbR] < ta.valuewhen(phFound, high[lbR], 1)
//_bear = (plotHidden and priceLH and rsiHH and phFound) ? 'Hidden Short Sig' : (priceHH and rsiLH and phFound) ?
//'Regular Short Sig' : 'Wait for Trade'
//_div = (plotHidden and priceHL and rsiLL and plFound) ? 'Hidden Long Sig' :
//(priceLL and rsiHL and plFound) ? 'Regular Long Sig' : (plotHidden and priceLH and rsiHH and phFound) ? 'Hidden Short Sig' : (priceHH and rsiLH and phFound) ?
//'Regular Short Sig' : 'Wait for Trade'
// [close, temp_rsi, high, adx, _div, bbr, ematema, arsi]
[close, temp_rsi, high, adx, bbr, ematema, arsi]
// Security call
[cl01, rsi01, High01, adx01, bbr01, ematema01, _adaSig01] = request.security(s01, timeframe.period, screener_func())
[cl02, rsi02, High02, adx02, bbr02, ematema02, _adaSig02] = request.security(s02, timeframe.period, screener_func())
[cl03, rsi03, High03, adx03, bbr03, ematema03, _adaSig03] = request.security(s03, timeframe.period, screener_func())
[cl04, rsi04, High04, adx04, bbr04, ematema04, _adaSig04] = request.security(s04, timeframe.period, screener_func())
[cl05, rsi05, High05, adx05, bbr05, ematema05, _adaSig05] = request.security(s05, timeframe.period, screener_func())
[cl06, rsi06, High06, adx06, bbr06, ematema06, _adaSig06] = request.security(s06, timeframe.period, screener_func())
[cl07, rsi07, High07, adx07, bbr07, ematema07, _adaSig07] = request.security(s07, timeframe.period, screener_func())
[cl08, rsi08, High08, adx08, bbr08, ematema08, _adaSig08] = request.security(s08, timeframe.period, screener_func())
[cl09, rsi09, High09, adx09, bbr09, ematema09, _adaSig09] = request.security(s09, timeframe.period, screener_func())
[cl10, rsi10, High10, adx10, bbr10, ematema10, _adaSig10] = request.security(s10, timeframe.period, screener_func())
[cl11, rsi11, High11, adx11, bbr11, ematema11, _adaSig11] = request.security(s11, timeframe.period, screener_func())
[cl12, rsi12, High12, adx12, bbr12, ematema12, _adaSig12] = request.security(s12, timeframe.period, screener_func())
[cl13, rsi13, High13, adx13, bbr13, ematema13, _adaSig13] = request.security(s13, timeframe.period, screener_func())
[cl14, rsi14, High14, adx14, bbr14, ematema14, _adaSig14] = request.security(s14, timeframe.period, screener_func())
[cl15, rsi15, High15, adx15, bbr15, ematema15, _adaSig15] = request.security(s15, timeframe.period, screener_func())
[cl16, rsi16, High16, adx16, bbr16, ematema16, _adaSig16] = request.security(s16, timeframe.period, screener_func())
[cl17, rsi17, High17, adx17, bbr17, ematema17, _adaSig17] = request.security(s17, timeframe.period, screener_func())
[cl18, rsi18, High18, adx18, bbr18, ematema18, _adaSig18] = request.security(s18, timeframe.period, screener_func())
[cl19, rsi19, High19, adx19, bbr19, ematema19, _adaSig19] = request.security(s19, timeframe.period, screener_func())
[cl20, rsi20, High20, adx20, bbr20, ematema20, _adaSig20] = request.security(s20, timeframe.period, screener_func())
[cl21, rsi21, High21, adx21, bbr21, ematema21, _adaSig21] = request.security(s21, timeframe.period, screener_func())
[cl22, rsi22, High22, adx22, bbr22, ematema22, _adaSig22] = request.security(s22, timeframe.period, screener_func())
[cl23, rsi23, High23, adx23, bbr23, ematema23, _adaSig23] = request.security(s23, timeframe.period, screener_func())
[cl24, rsi24, High24, adx24, bbr24, ematema24, _adaSig24] = request.security(s24, timeframe.period, screener_func())
[cl25, rsi25, High25, adx25, bbr25, ematema25, _adaSig25] = request.security(s25, timeframe.period, screener_func())
[cl26, rsi26, High26, adx26, bbr26, ematema26, _adaSig26] = request.security(s26, timeframe.period, screener_func())
[cl27, rsi27, High27, adx27, bbr27, ematema27, _adaSig27] = request.security(s27, timeframe.period, screener_func())
[cl28, rsi28, High28, adx28, bbr28, ematema28, _adaSig28] = request.security(s28, timeframe.period, screener_func())
[cl29, rsi29, High29, adx29, bbr29, ematema29, _adaSig29] = request.security(s29, timeframe.period, screener_func())
[cl30, rsi30, High30, adx30, bbr30, ematema30, _adaSig30] = request.security(s30, timeframe.period, screener_func())
[cl31, rsi31, High31, adx31, bbr31, ematema31, _adaSig31] = request.security(s31, timeframe.period, screener_func())
[cl32, rsi32, High32, adx32, bbr32, ematema32, _adaSig32] = request.security(s32, timeframe.period, screener_func())
[cl33, rsi33, High33, adx33, bbr33, ematema33, _adaSig33] = request.security(s33, timeframe.period, screener_func())
[cl34, rsi34, High34, adx34, bbr34, ematema34, _adaSig34] = request.security(s34, timeframe.period, screener_func())
[cl35, rsi35, High35, adx35, bbr35, ematema35, _adaSig35] = request.security(s35, timeframe.period, screener_func())
[cl36, rsi36, High36, adx36, bbr36, ematema36, _adaSig36] = request.security(s36, timeframe.period, screener_func())
[cl37, rsi37, High37, adx37, bbr37, ematema37, _adaSig37] = request.security(s37, timeframe.period, screener_func())
[cl38, rsi38, High38, adx38, bbr38, ematema38, _adaSig38] = request.security(s38, timeframe.period, screener_func())
[cl39, rsi39, High39, adx39, bbr39, ematema39, _adaSig39] = request.security(s39, timeframe.period, screener_func())
[cl40, rsi40, High40, adx40, bbr40, ematema40, _adaSig40] = request.security(s40, timeframe.period, screener_func())
////////////
// ARRAYS //
u_arr = array.new_bool(0)
s_arr = array.new_string(0)
cl_arr = array.new_float(0)
rsi_arr = array.new_float(0)
high_arr = array.new_float(0)
adx_arr = array.new_float(0)
//_div_arr = array.new_string(0)
bbr_arr = array.new_float(0)
ematema_arr = array.new_string(0)
_adaRSI_arr = array.new_float(0)
// Add Symbols
array.push(s_arr, only_symbol(s01))
array.push(s_arr, only_symbol(s02))
array.push(s_arr, only_symbol(s03))
array.push(s_arr, only_symbol(s04))
array.push(s_arr, only_symbol(s05))
array.push(s_arr, only_symbol(s06))
array.push(s_arr, only_symbol(s07))
array.push(s_arr, only_symbol(s08))
array.push(s_arr, only_symbol(s09))
array.push(s_arr, only_symbol(s10))
array.push(s_arr, only_symbol(s11))
array.push(s_arr, only_symbol(s12))
array.push(s_arr, only_symbol(s13))
array.push(s_arr, only_symbol(s14))
array.push(s_arr, only_symbol(s15))
array.push(s_arr, only_symbol(s16))
array.push(s_arr, only_symbol(s17))
array.push(s_arr, only_symbol(s18))
array.push(s_arr, only_symbol(s19))
array.push(s_arr, only_symbol(s20))
array.push(s_arr, only_symbol(s21))
array.push(s_arr, only_symbol(s22))
array.push(s_arr, only_symbol(s23))
array.push(s_arr, only_symbol(s24))
array.push(s_arr, only_symbol(s25))
array.push(s_arr, only_symbol(s26))
array.push(s_arr, only_symbol(s27))
array.push(s_arr, only_symbol(s28))
array.push(s_arr, only_symbol(s29))
array.push(s_arr, only_symbol(s30))
array.push(s_arr, only_symbol(s31))
array.push(s_arr, only_symbol(s32))
array.push(s_arr, only_symbol(s33))
array.push(s_arr, only_symbol(s34))
array.push(s_arr, only_symbol(s35))
array.push(s_arr, only_symbol(s36))
array.push(s_arr, only_symbol(s37))
array.push(s_arr, only_symbol(s38))
array.push(s_arr, only_symbol(s39))
array.push(s_arr, only_symbol(s40))
///////////
// FLAGS //
array.push(u_arr, u01)
array.push(u_arr, u02)
array.push(u_arr, u03)
array.push(u_arr, u04)
array.push(u_arr, u05)
array.push(u_arr, u06)
array.push(u_arr, u07)
array.push(u_arr, u08)
array.push(u_arr, u09)
array.push(u_arr, u10)
array.push(u_arr, u11)
array.push(u_arr, u12)
array.push(u_arr, u13)
array.push(u_arr, u14)
array.push(u_arr, u15)
array.push(u_arr, u16)
array.push(u_arr, u17)
array.push(u_arr, u18)
array.push(u_arr, u19)
array.push(u_arr, u20)
array.push(u_arr, u21)
array.push(u_arr, u22)
array.push(u_arr, u23)
array.push(u_arr, u24)
array.push(u_arr, u25)
array.push(u_arr, u26)
array.push(u_arr, u27)
array.push(u_arr, u28)
array.push(u_arr, u29)
array.push(u_arr, u30)
array.push(u_arr, u31)
array.push(u_arr, u32)
array.push(u_arr, u33)
array.push(u_arr, u34)
array.push(u_arr, u35)
array.push(u_arr, u36)
array.push(u_arr, u37)
array.push(u_arr, u38)
array.push(u_arr, u39)
array.push(u_arr, u40)
///////// //
// BB %B
array.push(bbr_arr, bbr01)
array.push(bbr_arr, bbr02)
array.push(bbr_arr, bbr03)
array.push(bbr_arr, bbr04)
array.push(bbr_arr, bbr05)
array.push(bbr_arr, bbr06)
array.push(bbr_arr, bbr07)
array.push(bbr_arr, bbr08)
array.push(bbr_arr, bbr09)
array.push(bbr_arr, bbr10)
array.push(bbr_arr, bbr11)
array.push(bbr_arr, bbr12)
array.push(bbr_arr, bbr13)
array.push(bbr_arr, bbr14)
array.push(bbr_arr, bbr15)
array.push(bbr_arr, bbr16)
array.push(bbr_arr, bbr17)
array.push(bbr_arr, bbr18)
array.push(bbr_arr, bbr19)
array.push(bbr_arr, bbr20)
array.push(bbr_arr, bbr21)
array.push(bbr_arr, bbr22)
array.push(bbr_arr, bbr23)
array.push(bbr_arr, bbr24)
array.push(bbr_arr, bbr25)
array.push(bbr_arr, bbr26)
array.push(bbr_arr, bbr27)
array.push(bbr_arr, bbr28)
array.push(bbr_arr, bbr29)
array.push(bbr_arr, bbr30)
array.push(bbr_arr, bbr31)
array.push(bbr_arr, bbr32)
array.push(bbr_arr, bbr33)
array.push(bbr_arr, bbr34)
array.push(bbr_arr, bbr35)
array.push(bbr_arr, bbr36)
array.push(bbr_arr, bbr37)
array.push(bbr_arr, bbr38)
array.push(bbr_arr, bbr39)
array.push(bbr_arr, bbr40)
///////////
// CLOSE //
array.push(cl_arr, cl01)
array.push(cl_arr, cl02)
array.push(cl_arr, cl03)
array.push(cl_arr, cl04)
array.push(cl_arr, cl05)
array.push(cl_arr, cl06)
array.push(cl_arr, cl07)
array.push(cl_arr, cl08)
array.push(cl_arr, cl09)
array.push(cl_arr, cl10)
array.push(cl_arr, cl11)
array.push(cl_arr, cl12)
array.push(cl_arr, cl13)
array.push(cl_arr, cl14)
array.push(cl_arr, cl15)
array.push(cl_arr, cl16)
array.push(cl_arr, cl17)
array.push(cl_arr, cl18)
array.push(cl_arr, cl19)
array.push(cl_arr, cl20)
array.push(cl_arr, cl21)
array.push(cl_arr, cl22)
array.push(cl_arr, cl23)
array.push(cl_arr, cl24)
array.push(cl_arr, cl25)
array.push(cl_arr, cl26)
array.push(cl_arr, cl27)
array.push(cl_arr, cl28)
array.push(cl_arr, cl29)
array.push(cl_arr, cl30)
array.push(cl_arr, cl31)
array.push(cl_arr, cl32)
array.push(cl_arr, cl33)
array.push(cl_arr, cl34)
array.push(cl_arr, cl35)
array.push(cl_arr, cl36)
array.push(cl_arr, cl37)
array.push(cl_arr, cl38)
array.push(cl_arr, cl39)
array.push(cl_arr, cl40)
/////////
// RSI //
array.push(rsi_arr, rsi01)
array.push(rsi_arr, rsi02)
array.push(rsi_arr, rsi03)
array.push(rsi_arr, rsi04)
array.push(rsi_arr, rsi05)
array.push(rsi_arr, rsi06)
array.push(rsi_arr, rsi07)
array.push(rsi_arr, rsi08)
array.push(rsi_arr, rsi09)
array.push(rsi_arr, rsi10)
array.push(rsi_arr, rsi11)
array.push(rsi_arr, rsi12)
array.push(rsi_arr, rsi13)
array.push(rsi_arr, rsi14)
array.push(rsi_arr, rsi15)
array.push(rsi_arr, rsi16)
array.push(rsi_arr, rsi17)
array.push(rsi_arr, rsi18)
array.push(rsi_arr, rsi19)
array.push(rsi_arr, rsi20)
array.push(rsi_arr, rsi21)
array.push(rsi_arr, rsi22)
array.push(rsi_arr, rsi23)
array.push(rsi_arr, rsi24)
array.push(rsi_arr, rsi25)
array.push(rsi_arr, rsi26)
array.push(rsi_arr, rsi27)
array.push(rsi_arr, rsi28)
array.push(rsi_arr, rsi29)
array.push(rsi_arr, rsi30)
array.push(rsi_arr, rsi31)
array.push(rsi_arr, rsi32)
array.push(rsi_arr, rsi33)
array.push(rsi_arr, rsi34)
array.push(rsi_arr, rsi35)
array.push(rsi_arr, rsi36)
array.push(rsi_arr, rsi37)
array.push(rsi_arr, rsi38)
array.push(rsi_arr, rsi39)
array.push(rsi_arr, rsi40)
/////////
// High
array.push(high_arr, High01)
array.push(high_arr, High02)
array.push(high_arr, High03)
array.push(high_arr, High04)
array.push(high_arr, High05)
array.push(high_arr, High06)
array.push(high_arr, High07)
array.push(high_arr, High08)
array.push(high_arr, High09)
array.push(high_arr, High10)
array.push(high_arr, High11)
array.push(high_arr, High12)
array.push(high_arr, High13)
array.push(high_arr, High14)
array.push(high_arr, High15)
array.push(high_arr, High16)
array.push(high_arr, High17)
array.push(high_arr, High18)
array.push(high_arr, High19)
array.push(high_arr, High20)
array.push(high_arr, High21)
array.push(high_arr, High22)
array.push(high_arr, High23)
array.push(high_arr, High24)
array.push(high_arr, High25)
array.push(high_arr, High26)
array.push(high_arr, High27)
array.push(high_arr, High28)
array.push(high_arr, High29)
array.push(high_arr, High30)
array.push(high_arr, High31)
array.push(high_arr, High32)
array.push(high_arr, High33)
array.push(high_arr, High34)
array.push(high_arr, High35)
array.push(high_arr, High36)
array.push(high_arr, High37)
array.push(high_arr, High38)
array.push(high_arr, High39)
array.push(high_arr, High40)
////////
//adx
array.push(adx_arr, adx01)
array.push(adx_arr, adx02)
array.push(adx_arr, adx03)
array.push(adx_arr, adx04)
array.push(adx_arr, adx05)
array.push(adx_arr, adx06)
array.push(adx_arr, adx07)
array.push(adx_arr, adx08)
array.push(adx_arr, adx09)
array.push(adx_arr, adx10)
array.push(adx_arr, adx11)
array.push(adx_arr, adx12)
array.push(adx_arr, adx13)
array.push(adx_arr, adx14)
array.push(adx_arr, adx15)
array.push(adx_arr, adx16)
array.push(adx_arr, adx17)
array.push(adx_arr, adx18)
array.push(adx_arr, adx19)
array.push(adx_arr, adx20)
array.push(adx_arr, adx21)
array.push(adx_arr, adx22)
array.push(adx_arr, adx23)
array.push(adx_arr, adx24)
array.push(adx_arr, adx25)
array.push(adx_arr, adx26)
array.push(adx_arr, adx27)
array.push(adx_arr, adx28)
array.push(adx_arr, adx29)
array.push(adx_arr, adx30)
array.push(adx_arr, adx31)
array.push(adx_arr, adx32)
array.push(adx_arr, adx33)
array.push(adx_arr, adx34)
array.push(adx_arr, adx35)
array.push(adx_arr, adx36)
array.push(adx_arr, adx37)
array.push(adx_arr, adx38)
array.push(adx_arr, adx39)
array.push(adx_arr, adx40)
/////////
// ematema //
array.push(ematema_arr, ematema01)
array.push(ematema_arr, ematema02)
array.push(ematema_arr, ematema03)
array.push(ematema_arr, ematema04)
array.push(ematema_arr, ematema05)
array.push(ematema_arr, ematema06)
array.push(ematema_arr, ematema07)
array.push(ematema_arr, ematema08)
array.push(ematema_arr, ematema09)
array.push(ematema_arr, ematema10)
array.push(ematema_arr, ematema11)
array.push(ematema_arr, ematema12)
array.push(ematema_arr, ematema13)
array.push(ematema_arr, ematema14)
array.push(ematema_arr, ematema15)
array.push(ematema_arr, ematema16)
array.push(ematema_arr, ematema17)
array.push(ematema_arr, ematema18)
array.push(ematema_arr, ematema19)
array.push(ematema_arr, ematema20)
array.push(ematema_arr, ematema21)
array.push(ematema_arr, ematema22)
array.push(ematema_arr, ematema23)
array.push(ematema_arr, ematema24)
array.push(ematema_arr, ematema25)
array.push(ematema_arr, ematema26)
array.push(ematema_arr, ematema27)
array.push(ematema_arr, ematema28)
array.push(ematema_arr, ematema29)
array.push(ematema_arr, ematema30)
array.push(ematema_arr, ematema31)
array.push(ematema_arr, ematema32)
array.push(ematema_arr, ematema33)
array.push(ematema_arr, ematema34)
array.push(ematema_arr, ematema35)
array.push(ematema_arr, ematema36)
array.push(ematema_arr, ematema37)
array.push(ematema_arr, ematema38)
array.push(ematema_arr, ematema39)
array.push(ematema_arr, ematema40)
////////////////
array.push(_adaRSI_arr, _adaSig01)
array.push(_adaRSI_arr, _adaSig02)
array.push(_adaRSI_arr, _adaSig03)
array.push(_adaRSI_arr, _adaSig04)
array.push(_adaRSI_arr, _adaSig05)
array.push(_adaRSI_arr, _adaSig06)
array.push(_adaRSI_arr, _adaSig07)
array.push(_adaRSI_arr, _adaSig08)
array.push(_adaRSI_arr, _adaSig09)
array.push(_adaRSI_arr, _adaSig10)
array.push(_adaRSI_arr, _adaSig11)
array.push(_adaRSI_arr, _adaSig12)
array.push(_adaRSI_arr, _adaSig13)
array.push(_adaRSI_arr, _adaSig14)
array.push(_adaRSI_arr, _adaSig15)
array.push(_adaRSI_arr, _adaSig16)
array.push(_adaRSI_arr, _adaSig17)
array.push(_adaRSI_arr, _adaSig18)
array.push(_adaRSI_arr, _adaSig19)
array.push(_adaRSI_arr, _adaSig20)
array.push(_adaRSI_arr, _adaSig21)
array.push(_adaRSI_arr, _adaSig22)
array.push(_adaRSI_arr, _adaSig23)
array.push(_adaRSI_arr, _adaSig24)
array.push(_adaRSI_arr, _adaSig25)
array.push(_adaRSI_arr, _adaSig26)
array.push(_adaRSI_arr, _adaSig27)
array.push(_adaRSI_arr, _adaSig28)
array.push(_adaRSI_arr, _adaSig29)
array.push(_adaRSI_arr, _adaSig30)
array.push(_adaRSI_arr, _adaSig31)
array.push(_adaRSI_arr, _adaSig32)
array.push(_adaRSI_arr, _adaSig33)
array.push(_adaRSI_arr, _adaSig34)
array.push(_adaRSI_arr, _adaSig35)
array.push(_adaRSI_arr, _adaSig36)
array.push(_adaRSI_arr, _adaSig37)
array.push(_adaRSI_arr, _adaSig38)
array.push(_adaRSI_arr, _adaSig39)
array.push(_adaRSI_arr, _adaSig40)
///////////
// PLOTS //
var tbl = table.new(string(i_s_Y +'_'+ i_s_X), 6, 41, border_color=color.new(#0f0000, 0))
if barstate.islast
table.cell(tbl, 0, 0, string('Symbol'+' -- '+"Price"), text_halign = text.align_center,
bgcolor = _colTable, text_color = _colText, text_size = i_s_font)
table.cell(tbl, 1, 0, 'Smooth Tema',text_halign = text.align_center, bgcolor = _colTable, text_color = _colText, text_size = i_s_font)
table.cell(tbl, 2, 0, 'RSI', text_halign = text.align_center, bgcolor = _colTable, text_color = _colText, text_size = i_s_font)
table.cell(tbl, 3, 0, 'Adap. RSI', text_halign = text.align_center, bgcolor = _colTable, text_color = _colText, text_size = i_s_font)
table.cell(tbl, 4, 0, 'ADX', text_halign = text.align_center, bgcolor = _colTable, text_color = _colText, text_size = i_s_font)
//table.cell(tbl, 5, 0, 'RSI Hidden', text_halign = text.align_center, bgcolor = _colTable, text_color = _colText, text_size = i_s_font)
table.cell(tbl, 5, 0, 'BB %B', text_halign = text.align_center, bgcolor = _colTable, text_color = _colText, text_size = i_s_font)
for i = 0 to 39
if array.get(u_arr, i)
_ema_col = array.get(ematema_arr,i) == "Up" ? bullish_col : array.get(ematema_arr,i)
== "Down" ? bearish_col : array.get(ematema_arr,i) == "Long" ? bullish_col : array.get(ematema_arr,i)
== "Short" ? bearish_col : array.get(ematema_arr,i) == "Wait For Signal" ? _colTable : na
//_div_col = array.get(_div_arr, i) == 'Regular Long Sig' ? bullish_col : array.get(_div_arr,i)
//== "Regular Short Sig" ? bearish_col : array.get(_div_arr, i) == "Hidden Long Sig" ? color.new(#43ebed, 0)
//: array.get(_div_arr, i) == "Hidden Short Sig" ? color.new(#c6642f, 0) : _colTable
_ada_col = array.get(_adaRSI_arr, i) > array.get(_adaRSI_arr[1], i) ? bullish_col
: array.get(_adaRSI_arr, i) < array.get(_adaRSI_arr[1], i) ? bearish_col : _colTable
adx_col = array.get(adx_arr, i) > 40 ? bullish_col : array.get(adx_arr, i) < 40 ? bearish_col : _colTable
rsi_col = array.get(rsi_arr, i) > _obLevel ? bearish_col : array.get(rsi_arr, i)
< _osLevel ? bullish_col : _colTable
symbol_text = string(array.get(s_arr, i)) +' -- '+ str.tostring(array.get(cl_arr, i))
symbol_col = array.get(cl_arr, i) > array.get(cl_arr[1], i) ? bullish_col
: array.get(cl_arr, i) < array.get(cl_arr[1],i) ? bearish_col : _colTable
table.cell(tbl, 0, i + 1, symbol_text, text_halign = text.align_left,
bgcolor = symbol_col, text_color = _colText, text_size = i_s_font)
table.cell(tbl, 1, i + 1, str.tostring(array.get(ematema_arr, i)), text_halign = text.align_center,
bgcolor = _ema_col, text_color = _colText, text_size = i_s_font)
table.cell(tbl, 2, i + 1, str.tostring(array.get(rsi_arr, i), "#.##"),text_halign = text.align_center,
bgcolor = rsi_col, text_color = _colText, text_size = i_s_font)
//table.cell(tbl, 5, i + 1, str.tostring(array.get(_div_arr, i)), text_halign = text.align_center,
//bgcolor = _div_col , text_color = _colText, text_size = i_s_font)
table.cell(tbl, 3, i + 1, str.tostring(array.get(_adaRSI_arr, i)), text_halign = text.align_center,
bgcolor = _ada_col , text_color = _colText, text_size = i_s_font)
table.cell(tbl, 4, i + 1, str.tostring(array.get(adx_arr, i)), text_halign = text.align_center,
bgcolor = adx_col, text_color = _colText, text_size = i_s_font)
table.cell(tbl, 5, i + 1, str.tostring(array.get(bbr_arr, i)), text_halign = text.align_center,
bgcolor = _colTable, text_color = _colText, text_size = i_s_font)
|
Monthly Options Expiration 2023 | https://www.tradingview.com/script/fBI2MnjA-Monthly-Options-Expiration-2023/ | imzeeshan | https://www.tradingview.com/u/imzeeshan/ | 31 | 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/
// Source: https://www.marketwatch.com/tools/options-expiration-calendar?year=2023
// © imzeeshan
//@version=5
indicator("Monthly Options Expiration 2023", overlay=true)
expiry=year==2022 and month==12 and dayofmonth==16 and timeframe.isdaily
c=input('F', title="Character")
o=input(7, title="X bars before")
jan=22
feb=jan+20+0
mar=feb+20-1
apr=mar+20+4
may=apr+20+0
jun=may+20-1
jul=jun+20+3
aug=jul+20+0
sep=aug+20-1
oct=sep+20+5
nov=oct+20+0
dec=nov+20-1
// Expirations
plotchar(expiry, title="Jan", char=c, location = location.bottom, color=color.blue, offset=jan, editable=false)
plotchar(expiry, title="Feb", char=c, location = location.bottom, color=color.blue, offset=feb, editable=false)
plotchar(expiry, title="Mar", char=c, location = location.bottom, color=color.blue, offset=mar, editable=false)
plotchar(expiry, title="Apr", char=c, location = location.bottom, color=color.blue, offset=apr, editable=false)
plotchar(expiry, title="May", char=c, location = location.bottom, color=color.blue, offset=may, editable=false)
plotchar(expiry, title="Jun", char=c, location = location.bottom, color=color.blue, offset=jun, editable=false)
plotchar(expiry, title="Jul", char=c, location = location.bottom, color=color.blue, offset=jul, editable=false)
plotchar(expiry, title="Aug", char=c, location = location.bottom, color=color.blue, offset=aug, editable=false)
plotchar(expiry, title="Sep", char=c, location = location.bottom, color=color.blue, offset=sep, editable=false)
plotchar(expiry, title="Oct", char=c, location = location.bottom, color=color.blue, offset=oct, editable=false)
plotchar(expiry, title="Nov", char=c, location = location.bottom, color=color.blue, offset=nov, editable=false)
plotchar(expiry, title="Dec", char=c, location = location.bottom, color=color.blue, offset=dec, editable=false)
// Last week of expirations
plotshape(expiry, style=shape.flag, location = location.bottom, color=color.blue, offset=jan-o, editable=false)
plotshape(expiry, style=shape.flag, location = location.bottom, color=color.blue, offset=feb-o, editable=false)
plotshape(expiry, style=shape.flag, location = location.bottom, color=color.blue, offset=mar-o, editable=false)
plotshape(expiry, style=shape.flag, location = location.bottom, color=color.blue, offset=apr-o, editable=false)
plotshape(expiry, style=shape.flag, location = location.bottom, color=color.blue, offset=may-o, editable=false)
plotshape(expiry, style=shape.flag, location = location.bottom, color=color.blue, offset=jun-o, editable=false)
plotshape(expiry, style=shape.flag, location = location.bottom, color=color.blue, offset=jul-o, editable=false)
plotshape(expiry, style=shape.flag, location = location.bottom, color=color.blue, offset=aug-o, editable=false)
plotshape(expiry, style=shape.flag, location = location.bottom, color=color.blue, offset=sep-o, editable=false)
plotshape(expiry, style=shape.flag, location = location.bottom, color=color.blue, offset=oct-o, editable=false)
plotshape(expiry, style=shape.flag, location = location.bottom, color=color.blue, offset=nov-o, editable=false)
plotshape(expiry, style=shape.flag, location = location.bottom, color=color.blue, offset=dec-o, editable=false)
// Start of month
show_som=input(true, title="Start of month")
som = show_som and year==2023 and month!=month[1]
plotshape(som, style=shape.circle, location = location.bottom, color=color.blue, editable=false) |
Trend Oscillator | https://www.tradingview.com/script/eEjV4Ura-Trend-Oscillator/ | faytterro | https://www.tradingview.com/u/faytterro/ | 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/
// © faytterro
//@version=5
indicator("Trend Oscillator", timeframe = "", timeframe_gaps = true)
srctcr=input(hlc3,title="source")
lentcr=input.int(25,title="lenght", maxval=1000)
cr(x, y) =>
z = 0.0
w = 0.0
for i = 0 to y-1
z:=z + x[i]*(-math.cos((22/7)*2*(i)/(y+1))*(y+1)/4+(y+1)/4)
w:= w + (-math.cos((22/7)*2*(i)/(y+1))*(y+1)/4+(y+1)/4)
z/w
cr= cr(srctcr,2*lentcr-1)
mom = ta.change(cr)
ac = ta.change(mom)
x = (mom>0 and ac>0)? 2 :
(mom>0 and ac<0)? 1 :
(mom<0 and ac<0)? -2 :
(mom<0 and ac>0)? -1 : na
y = ta.cum(x)
plot(y, color = x>1? color.rgb(0, 255, 0) : x<-1? color.rgb(255, 0, 0) :
x>0? color.rgb(155, 255, 0) : color.rgb(255, 155, 0), linewidth = 2)
plot(ta.sma(y,100), trackprice = true, display = display.none, color = color.rgb(255, 255, 255))
dip = x[1]==-1 and x==2
tepe = x[1]==1 and x==-2
bgcolor(color= dip? color.green : tepe? color.red : na, display = display.none)
alertcondition(dip, "Trend Oscillator swing low alert")
alertcondition(tepe, "Trend Oscillator swing high alert") |
Take Session High/Low Alert [MsF] | https://www.tradingview.com/script/QOPD6ZXK/ | Trader_Morry | https://www.tradingview.com/u/Trader_Morry/ | 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/
// © Trader_Morry
//@version=5
indicator(title='Take Session High/Low Alert [MsF]', shorttitle='TS High/Low', overlay=true, max_bars_back = 5000)
////////
// Input values
// [
var GRP1 = "--- Vertical Lines setting ---"
sessionTime_60_00 = input.session("0000-0800", title="Session time", group = GRP1)
sessionTime_40_60 = input.session("0800-1300", title="Session time", group = GRP1)
sessionTime_20_40 = input.session("1300-1900", title="Session time", group = GRP1)
sessionTime_00_20 = input.session("1900-2400", title="Session time", group = GRP1)
sessionZone = input.string("GMT-5", title="Session time zone", group = GRP1)
lineColor_00 = input.color(defval=color.rgb( 255, 235, 59, 50), title='Basis color', inline='00', group = GRP1)
lineStyle_00 = input.string(title='Style', defval=line.style_solid, options=[line.style_dotted, line.style_dashed, line.style_solid], inline = "00", group = GRP1)
lineColor_XX = input.color(defval=color.rgb( 255, 255, 255, 70), title='Other color', inline='XX', group = GRP1)
lineStyle_XX = input.string(title='Style', defval=line.style_solid, options=[line.style_dotted, line.style_dashed, line.style_solid], inline = "XX", group = GRP1)
enableTimeLines = input.bool(defval=true, title="Enable Time Lines", group = GRP1)
var GRP2 = "--- Horizontal Lines setting ---"
lineColor_HL = input.color(defval=color.blue, title='High / Low color', inline='HL', group = GRP2)
lineStyle_HL = input.string(title='Style', defval=line.style_solid, options=[line.style_dotted, line.style_dashed, line.style_solid], inline = "HL", group = GRP2)
lineColor_CR = input.color(defval=color.red, title='Taken Line color', inline='CR', group = GRP2)
lineStyle_CR = input.string(title='Style', defval=line.style_dotted, options=[line.style_dotted, line.style_dashed, line.style_solid], inline = "CR", group = GRP2)
iExtend = input.bool(true, title="Extend Lines", group = GRP2)
iEBLineCnt = input.int(0, title="Extend Broken Line Count", group = GRP2)
// ]
// *** Draw Vertical Lines ***
////////
// Preparing
// [
// Get day open
[dailyTime, dailyOpen] = request.security(syminfo.tickerid, 'D', [time, open], lookahead=barmerge.lookahead_on)
// Get timestamp
sessionTime_00_VL_hh = str.tonumber(str.substring(sessionTime_00_20,0,2))
sessionTime_20_VL_hh = str.tonumber(str.substring(sessionTime_20_40,0,2))
sessionTime_40_VL_hh = str.tonumber(str.substring(sessionTime_40_60,0,2))
sessionTime_60_VL_hh = str.tonumber(str.substring(sessionTime_60_00,0,2))
sessionTime_00_VL_m2 = str.tonumber(str.substring(sessionTime_00_20,2,4))
sessionTime_20_VL_m2 = str.tonumber(str.substring(sessionTime_20_40,2,4))
sessionTime_40_VL_m2 = str.tonumber(str.substring(sessionTime_40_60,2,4))
sessionTime_60_VL_m2 = str.tonumber(str.substring(sessionTime_60_00,2,4))
iBaseTime_00 = timestamp(sessionZone, year, month, dayofmonth, int(sessionTime_60_VL_hh), int(sessionTime_60_VL_m2), 0) // NY time 00:00
iBaseTime_20 = timestamp(sessionZone, year, month, dayofmonth, int(sessionTime_40_VL_hh), int(sessionTime_40_VL_m2), 0) // NY time 08:00
iBaseTime_40 = timestamp(sessionZone, year, month, dayofmonth, int(sessionTime_20_VL_hh), int(sessionTime_20_VL_m2), 0) // NY time 13:00
iBaseTime_60 = timestamp(sessionZone, year, month, dayofmonth, int(sessionTime_00_VL_hh), int(sessionTime_00_VL_m2), 0) // NY time 19:00
// Initializing Flag
var iDrawTimeD_00 = 0
var iDrawTimeD_20 = 0
var iDrawTimeD_40 = 0
var iDrawTimeD_60 = 0
// ]
////////
// Function
// [
drawing_VerticalLines(aBaseTime, aDrawTimeD, aLineStyle, aLineColor) =>
_iDrawTimeD = aDrawTimeD
yy = year
mm = month
dd = dayofmonth
hh = hour(aBaseTime)
m2 = minute(aBaseTime)
iDrawTime = timestamp(yy, mm, dd, hh, m2)
// 土曜~月曜までは休場なので線がおかしくなる。その対応
hour_j = hour(iDrawTime, "GMT+9")
dayofweek_j = dayofweek(iDrawTime, "GMT+9")
iDsp = true
if dayofweek_j == dayofweek.saturday and hour_j >= 6
iDsp := false
else if dayofweek_j == dayofweek.sunday
iDsp := false
else if dayofweek_j == dayofweek.monday and hour_j < 7
iDsp := false
// cryptoは24時間動いているので休場対応からは除外
if syminfo.type == "crypto"
iDsp := true
// double drawing prevention
if iDrawTime != aDrawTimeD and iDsp
line.new(iDrawTime, dailyOpen, iDrawTime, dailyOpen + syminfo.mintick, xloc=xloc.bar_time, style=aLineStyle, extend=extend.both, color=aLineColor, width=1)
_iDrawTimeD := iDrawTime
_iDrawTimeD
// ]
////////
// Drawing Vertical Lines
// [
// H1を超える時間足は出力しない
if timeframe.in_seconds(timeframe.period) <= 3600 and enableTimeLines
iDrawTimeD_00 := drawing_VerticalLines(iBaseTime_00, iDrawTimeD_00, lineStyle_00, lineColor_00)
iDrawTimeD_20 := drawing_VerticalLines(iBaseTime_20, iDrawTimeD_20, lineStyle_XX, lineColor_XX)
iDrawTimeD_40 := drawing_VerticalLines(iBaseTime_40, iDrawTimeD_40, lineStyle_XX, lineColor_XX)
iDrawTimeD_60 := drawing_VerticalLines(iBaseTime_60, iDrawTimeD_60, lineStyle_XX, lineColor_XX)
// ]
// *** Draw Horizonal Lines ***
////////
// Preparing
// [
var max_array_size = 16
var sessionLineHArray = array.new_line()
var sessionLineLArray = array.new_line()
var sessionLineHArray_c = array.new_bool() // クロスしたかどうかのフラグは別に持つ
var sessionLineLArray_c = array.new_bool() // クロスしたかどうかのフラグは別に持つ
// ]
////////
// Function
// [
InSession(sessionTime, sessionTimeZone=syminfo.timezone) =>
not na(time(timeframe.period, sessionTime, sessionTimeZone))
add_to_Line(pointer, pointer_c, aLine) =>
array.unshift(pointer, aLine)
array.unshift(pointer_c, false)
if array.size(pointer) > max_array_size
array.pop(pointer)
array.pop(pointer_c)
drawing_HorizonalLines(aSessionTime, aSessionZone) =>
// Create variables
var sessionHighPrice = 0.0
var sessionLowPrice = 0.0
var sessionOpenPrice = 0.0
var line sessionLineH = na
var line sessionLineL = na
// See if the session is currently active and just started
inSession = InSession(aSessionTime, aSessionZone) and timeframe.isintraday
sessionStart = inSession and not inSession[1]
// When a new session starts, set the session high and low to the data
// of the bar in the session.
if sessionStart
sessionHighPrice := high
sessionLowPrice := low
sessionOpenPrice := open
// Else, during the session, track the highest high and lowest low
else if inSession
sessionHighPrice := math.max(sessionHighPrice, high)
sessionLowPrice := math.min(sessionLowPrice, low)
// When a session begins, make a new box for that session
if sessionStart
sessionLineH := line.new(bar_index,na,na,na,color = color.rgb(0,0,255,100))
sessionLineL := line.new(bar_index,na,na,na,color = color.rgb(0,0,255,100))
add_to_Line(sessionLineHArray, sessionLineHArray_c, sessionLineH)
add_to_Line(sessionLineLArray, sessionLineLArray_c, sessionLineL)
// During the session, update that session's existing box
if inSession
line.set_y1(sessionLineH, sessionHighPrice)
line.set_y2(sessionLineH, sessionHighPrice)
line.set_y1(sessionLineL, sessionLowPrice)
line.set_y2(sessionLineL, sessionLowPrice)
line.set_x2(sessionLineH, bar_index + 1)
line.set_x2(sessionLineL, bar_index + 1)
if iExtend
line.set_extend(sessionLineH, extend.right)
line.set_extend(sessionLineL, extend.right)
// ]
////////
// Drawing Vertical Lines
// [
// H1を超える時間足は出力しない
if timeframe.in_seconds(timeframe.period) <= 3600
drawing_HorizonalLines(sessionTime_00_20, sessionZone)
drawing_HorizonalLines(sessionTime_20_40, sessionZone)
drawing_HorizonalLines(sessionTime_40_60, sessionZone)
drawing_HorizonalLines(sessionTime_60_00, sessionZone)
// ]
// ]
// Cross the Vertical Lines Notification
// *attention! This procesure must write before Checking Cross the Vertical Lines
// [
check_Alert_Condition_H() =>
crossVHLines = false
if array.size(sessionLineHArray) > 1
for i = 1 to array.size(sessionLineHArray)-1
if line.get_y2(array.get(sessionLineHArray, i)) <= high
if not array.get(sessionLineHArray_c, i)
crossVHLines := true
crossVHLines
check_Alert_Condition_L() =>
crossVLLines = false
if array.size(sessionLineLArray) > 1
for i = 1 to array.size(sessionLineLArray)-1
if line.get_y2(array.get(sessionLineLArray, i)) >= low
if not array.get(sessionLineLArray_c, i)
crossVLLines := true
crossVLLines
alertcondition(check_Alert_Condition_H() , title='Taken High Key Lv.', message='Taken High Key Level Line Alert!')
alertcondition(check_Alert_Condition_L() , title='Taken Low Key Lv.', message='Taken Low Key Level Line Alert!')
// ]
////////
// Checking Cross the Vertical Lines
// [
if array.size(sessionLineHArray) > 1
for i = 1 to array.size(sessionLineHArray)-1
if line.get_y2(array.get(sessionLineHArray, i)) <= high
line.set_color(array.get(sessionLineHArray, i), lineColor_CR)
line.set_style(array.get(sessionLineHArray, i), lineStyle_CR)
if iEBLineCnt <= i
line.set_extend(array.get(sessionLineHArray, i), extend.none)
array.set(sessionLineHArray_c, i, true) // クロスした
else
if not array.get(sessionLineHArray_c, i)
line.set_color(array.get(sessionLineHArray, i), lineColor_HL)
if array.size(sessionLineLArray) > 1
for i = 1 to array.size(sessionLineLArray)-1
if line.get_y2(array.get(sessionLineLArray, i)) >= low
line.set_color(array.get(sessionLineLArray, i), lineColor_CR)
line.set_style(array.get(sessionLineLArray, i), lineStyle_CR)
if iEBLineCnt <= i
line.set_extend(array.get(sessionLineLArray, i), extend.none)
array.set(sessionLineLArray_c, i, true) // クロスした
else
if not array.get(sessionLineLArray_c, i)
line.set_color(array.get(sessionLineLArray, i), lineColor_HL)
line.set_style(array.get(sessionLineLArray, i), lineStyle_HL)
// ]
|
MA Band Distance Monitor | https://www.tradingview.com/script/704X2kH7-MA-Band-Distance-Monitor/ | HasanRifat | https://www.tradingview.com/u/HasanRifat/ | 278 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © HasanRifat
//@version=5
indicator("MA Band Distance Monitor", overlay = true, max_labels_count = 500)
// array for calculations
var slowMAdis = array.new_float()
var fastMAdis = array.new_float()
var maDisBtin = array.new_float()
arraySource = close
// MA input
slowlen = input.int(200, title="Slow MA Length", minval=1, tooltip = "Slow lenght input must be greater than fast length input, otherwise indicator will produce faulty results")
fastlen = input.int(50, title="Fast MA Length", minval=1, tooltip = "Fast lenght input must be less than slow length input, otherwise indicator will produce faulty results")
slowsrc = input(close, title="Slow MA Source")
fastsrc = input(close, title="Fast MA Source")
slowMAtype = input.string(defval = "SMA", title = "Slow MA Method", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"])
fastMAtype = input.string(defval = "SMA", title = "Fast MA Method", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"])
// table input
showTable = input.bool(true, "Show Table")
tablePosInput = input.string(title="Position", defval="Top Right", options=["Bottom Left", "Bottom Right", "Top Left", "Top Right"], tooltip="Select where you want the table to draw.")
var tablePos = tablePosInput == "Bottom Left" ? position.bottom_left : tablePosInput == "Bottom Right" ? position.bottom_right : tablePosInput == "Top Left" ? position.top_left : tablePosInput == "Top Right" ? position.top_right : na
//color
color1 = input.color(color.new(color.yellow , 35), 'color 1')
color2 = input.color(color.new(color.lime , 35), 'color 2')
color3 = input.color(color.new(color.red , 35), 'color 3')
maBandFill = input.bool (true,'fill')
// MA function
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)
// array function
f_array(source, speedMA, arrayC) =>
if source > speedMA
array.push(arrayC, source - speedMA)
if source < speedMA
array.push(arrayC, speedMA - source)
arrayC
slowMA = ma(slowsrc, slowlen, slowMAtype)
fastMA = ma(fastsrc, fastlen, fastMAtype)
slowMAarray = f_array(arraySource, slowMA, slowMAdis)
fastArray = f_array(arraySource, fastMA, fastMAdis)
array.push(maDisBtin, slowMA > fastMA ? slowMA - fastMA : fastMA - slowMA)
// calculation
slowMAavgDis = array.avg(slowMAdis)
fastMAavgDis = array.avg(fastMAdis)
maAvgDisBtin = array.avg(maDisBtin)
slowMACrrDis = close > slowMA ? math.round_to_mintick(close - slowMA) : math.round_to_mintick(slowMA - close)
fastMACrrDis = close > fastMA ? math.round_to_mintick(close - fastMA) : math.round_to_mintick(fastMA - close)
maCrrDis = slowMA > fastMA ? math.round_to_mintick(slowMA - fastMA) : math.round_to_mintick(fastMA - slowMA)
slowPlt = plot(slowMA, "Slow MA", color = na)
fastPlt = plot(fastMA, "Fast MA", color = na)
topVal = slowMA > fastMA ? math.min(slowMA, fastMA) : math.max(slowMA, fastMA)
botVal = slowMA > fastMA ? math.max(slowMA, fastMA) : math.min(slowMA, fastMA)
topClr = maBandFill ? slowMA > fastMA ? color1 : color2 : na
botClr = maBandFill ? slowMA > fastMA ? color3 : color1 : na
fill(slowPlt, fastPlt, topVal, botVal, topClr, botClr)
// table color
strongRed = color.rgb(255, 25, 25, 25)
weakRed = color.rgb(255, 82, 82, 25)
strongGreen = color.rgb(19, 200, 25, 25)
weakGreen = color.rgb(76, 175, 80, 25)
blue = color.rgb(20, 123, 134, 25)
//
var dataTable = table.new(tablePos, columns = 4, rows = 5, border_color = color.rgb(40, 40, 40, 25), border_width = 2)
if showTable
table.cell(dataTable, 1, 1, text = "Difference: ", bgcolor = blue, text_color = color.white)
table.cell(dataTable, 1, 2, text = "Slow MA"+"("+str.tostring(slowlen)+")", bgcolor = blue, text_color = color.white)
table.cell(dataTable, 1, 3, text = "Fast MA"+"("+str.tostring(fastlen)+") ", bgcolor = blue, text_color = color.white)
table.cell(dataTable, 1, 4, text = "Between MA ", bgcolor = blue, text_color = color.white)
table.cell(dataTable, 2, 1, text = "Average ", bgcolor = blue, text_color = color.white)
table.cell(dataTable, 3, 1, text = "Current ", bgcolor = blue, text_color = color.white)
table.cell(dataTable, 2, 2, text = str.tostring(math.round_to_mintick(slowMAavgDis)), bgcolor = close > slowMA ? weakGreen : weakRed, text_color = color.white)
table.cell(dataTable, 3, 2, text = str.tostring(slowMACrrDis), bgcolor = close > slowMA ? weakGreen : weakRed, text_color = color.white)
table.cell(dataTable, 2, 3, text = str.tostring(math.round_to_mintick(fastMAavgDis)), bgcolor = close > fastMA ? weakGreen : weakRed, text_color = color.white)
table.cell(dataTable, 3, 3, text = str.tostring(fastMACrrDis), bgcolor = close > fastMA ? weakGreen : weakRed, text_color = color.white)
table.cell(dataTable, 2, 4, text = str.tostring(math.round_to_mintick(fastMACrrDis)), bgcolor = fastMA > slowMA ? weakGreen : weakRed, text_color = color.white)
table.cell(dataTable, 3, 4, text = str.tostring(maCrrDis), bgcolor = fastMA > slowMA ? weakGreen : weakRed, text_color = color.white)
// alert
crossOver = ta.crossover(fastMA, slowMA)
crossUnder = ta.crossunder(fastMA, slowMA)
alertcondition(crossOver, "Bullish Crossover", "Bullish Crossover")
alertcondition(crossUnder, "Bearish CrossUnder", "Bearish Crossunder")
|
Bar metrics / quantifytools | https://www.tradingview.com/script/vhpAMHyU-Bar-metrics-quantifytools/ | quantifytools | https://www.tradingview.com/u/quantifytools/ | 178 | 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/
// © quantifytools
//@version=5
indicator("Bar metrics", overlay=true)
// Inputs
//Lookback inputs
groupLook = "General"
i_smoothingType = input.string("SMA", "Moving average", options=["SMA", "EMA", "HMA", "RMA", "WMA", "Median"], inline="source", group=groupLook, tooltip="Define average for relative volume/volatility calculations")
i_length = input.int(20, "", inline="source", group=groupLook, minval=1)
i_lookback = input.int(0, "Lookback", minval=0, group=groupLook, tooltip="Shows bar metric data for a bar that is X amount of bars back")
//Basket inputs
groupSym = "Basket average"
i_basketSyms = input.int(0, "Symbols included", minval=0, maxval=10, group=groupSym, tooltip="Select symbols that are included in average bar metric calculations. Useful for comparing broader market/comparable symbol metrics to current chart metrics. Keep at 0 to disable.")
sym1 = input.symbol("BTCUSDT", "#1", group=groupSym, inline="12")
sym2 = input.symbol("ETHUSDT", "#2", group=groupSym, inline="12")
sym3 = input.symbol("BNBUSDT", "#3", group=groupSym, inline="34")
sym4 = input.symbol("XRPUSDT", "#4", group=groupSym, inline="34")
sym5 = input.symbol("ADAUSDT", "#5", group=groupSym, inline="56")
sym6 = input.symbol("SOLUSDT", "#6", group=groupSym, inline="56")
sym7 = input.symbol("DOTUSDT", "#7", group=groupSym, inline="78")
sym8 = input.symbol("DOGEUSDT", "#8", group=groupSym, inline="78")
sym9 = input.symbol("XMRUSDT", "#9", group=groupSym, inline="910")
sym10 = input.symbol("MATICUSDT", "#10", group=groupSym,inline="910")
//Bar highlighter inputs
groupBar = "Bar highlights"
i_barCol = input.color(color.fuchsia, "", inline="hlight", group=groupBar)
i_highlightBool = input.bool(false, "Enable highlights & alerts", inline="hlight", group=groupBar, tooltip="Enable to highlight bars that are within specified bar metric bracket values. Keep this setting on when setting an alert.")
i_rVolume1 = input.float(0, "Relative volume", minval=0, group=groupBar, inline="rvolume", step=0.1)
i_rVolume2 = input.float(2, " - ", minval=0, group=groupBar, inline="rvolume", step=0.1)
i_rVolumeBool = input.bool(true, "", inline="rvolume", group=groupBar)
i_rVol1 = input.float(0, "Relative volatility", minval=0, group=groupBar, inline="rvol", step=0.1)
i_rVol2 = input.float(2, " - ", minval=0, group=groupBar, inline="rvol", step=0.1)
i_rVolBool = input.bool(true, "", inline="rvol", group=groupBar)
i_close1 = input.float(0, "Relative close", minval=0, maxval=100, group=groupBar, inline="rclose", step=5)
i_close2 = input.float(100, " - ", minval=0, maxval=100, group=groupBar, inline="rclose", step=5)
i_closeBool = input.bool(true, "", inline="rclose", group=groupBar)
//Table/label inputs
groupLT = "Metrics"
i_labelBool = input.bool(true, "Enable label", group=groupLT)
i_labelSize = input.int(2, "Label size", maxval=5, minval=1, group=groupLT)
i_offset = input.int(1, "Label offset", maxval=50, minval=1, group=groupLT)
i_tableBool = input.bool(false, "Enable table", group=groupLT)
tableSize = input.int(3, "Table size", maxval=5, minval=1, group=groupLT)
tablePos = input.string("Top right", "Table position", options=["Top right", "Bottom right", "Bottom left", "Top left"], group=groupLT)
//Plot related inputs
groupVol = "Relative volume/volatility"
i_vol1 = input.color(color.white, "Neutral", inline="vol", group=groupVol)
i_vol2 = input.color(color.yellow, "Light", inline="vol", group=groupVol)
i_vol3 = input.color(color.orange, "Medium", inline="vol", group=groupVol)
i_vol4 = input.color(color.red, "Heavy", inline="vol", group=groupVol)
groupRange = "Relative close"
i_neutralRange = input.color(color.white, "Neutral", inline="range", group=groupRange)
i_lightBullRange = input.color(color.teal, "Light ▲", inline="range", group=groupRange)
i_heavyBullRange = input.color(color.lime, "Heavy ▲", inline="range", group=groupRange)
i_lightBearRange = input.color(color.maroon, "Light ▼", inline="range", group=groupRange)
i_heavyBearRange = input.color(color.red, "Heavy ▼", inline="range", group=groupRange)
groupText = "Text"
i_text = input.color(color.white, "Text color", group=groupText, inline="text")
i_textBool = input.bool(false, "Stealth", group=groupText, inline="text")
// rVolume, rVolatility and rClose metrics
//User defined source and smoothing
smoothedValue(source, length) =>
i_smoothingType == "SMA" ? ta.sma(source, length) : i_smoothingType == "EMA" ? ta.ema(source, length) :
i_smoothingType == "HMA" ? ta.hma(source, length) : i_smoothingType == "RMA" ? ta.rma(source, length) :
i_smoothingType == "Median" ? ta.median(source, length) : ta.wma(source, length)
//Volume multiplier
volumeMa = smoothedValue(volume, i_length)
volumeMult = volume / volumeMa
volumeMultRounded = math.round(volume / volumeMa, 2)
//Volatility multiplier
volatility = high - low
volMa = smoothedValue(volatility, i_length)
volMult = volatility / volMa
volMultRounded = math.round(volatility / volMa, 2)
//Relative close
rangePos = (close - low) / (high - low)
rangePerc = math.round(rangePos * 100, 0)
// Bar highlighter
//Volatility within bracket values condition
volatilityCond = i_rVolBool ? volMult >= i_rVol1 and volMult <= i_rVol2 : na(close) == false
//Volume within bracket values condition
volumeCond = i_rVolumeBool ? volumeMult >= i_rVolume1 and volumeMult <= i_rVolume2 : na(close) == false
//Close within bracket values condition
closeCond = i_closeBool ? rangePerc >= i_close1 and rangePerc <= i_close2 : na(close) == false
//All conditions combined
allConds = volatilityCond and volumeCond and closeCond
// Basket average metrics
//Function for fetching relative volume/volatility/close
basketVal() =>
[volumeMultRounded, volMultRounded, rangePerc]
//Fetching bar metrics from chosen symbols
[volumeMult1, volMult1, rangePerc1] = request.security(sym1, timeframe.period, basketVal())
[volumeMult2, volMult2, rangePerc2] = request.security(sym2, timeframe.period, basketVal())
[volumeMult3, volMult3, rangePerc3] = request.security(sym3, timeframe.period, basketVal())
[volumeMult4, volMult4, rangePerc4] = request.security(sym4, timeframe.period, basketVal())
[volumeMult5, volMult5, rangePerc5] = request.security(sym5, timeframe.period, basketVal())
[volumeMult6, volMult6, rangePerc6] = request.security(sym6, timeframe.period, basketVal())
[volumeMult7, volMult7, rangePerc7] = request.security(sym7, timeframe.period, basketVal())
[volumeMult8, volMult8, rangePerc8] = request.security(sym8, timeframe.period, basketVal())
[volumeMult9, volMult9, rangePerc9] = request.security(sym9, timeframe.period, basketVal())
[volumeMult10, volMult10, rangePerc10] = request.security(sym10, timeframe.period, basketVal())
//Forming average relative volume
basketVolumeMult = i_basketSyms > 0 ? i_basketSyms == 1 ? volumeMult1 : i_basketSyms == 2 ? (volumeMult1 + volumeMult2) / i_basketSyms :
i_basketSyms == 3 ? (volumeMult1 + volumeMult2 + volumeMult3) / i_basketSyms : i_basketSyms == 4 ? (volumeMult1 + volumeMult2 + volumeMult3 + volumeMult4) / i_basketSyms :
i_basketSyms == 5 ? (volumeMult1 + volumeMult2 + volumeMult3 + volumeMult4 + volumeMult5) / i_basketSyms : i_basketSyms == 6 ? (volumeMult1 + volumeMult2 + volumeMult3 + volumeMult4 + volumeMult5 + volumeMult6) / i_basketSyms :
i_basketSyms == 7 ? (volumeMult1 + volumeMult2 + volumeMult3 + volumeMult4 + volumeMult5 + volumeMult6 + volumeMult7) / i_basketSyms : i_basketSyms == 8 ? (volumeMult1 + volumeMult2 + volumeMult3 + volumeMult4 + volumeMult5 + volumeMult6 + volumeMult7 + volumeMult8) / i_basketSyms :
i_basketSyms == 9 ? (volumeMult1 + volumeMult2 + volumeMult3 + volumeMult4 + volumeMult5 + volumeMult6 + volumeMult7 + volumeMult8 + volumeMult9) / i_basketSyms : i_basketSyms == 10 ? (volumeMult1 + volumeMult2 + volumeMult3 + volumeMult4 + volumeMult5 + volumeMult6 + volumeMult7 + volumeMult8 + volumeMult9 + volumeMult10) / i_basketSyms : na : na
//Forming average relative volatility
basketVolMult = i_basketSyms > 0 ? i_basketSyms == 1 ? volMult1 : i_basketSyms == 2 ? (volMult1 + volMult2) / i_basketSyms :
i_basketSyms == 3 ? (volMult1 + volMult2 + volMult3) / i_basketSyms : i_basketSyms == 4 ? (volMult1 + volMult2 + volMult3 + volMult4) / i_basketSyms :
i_basketSyms == 5 ? (volMult1 + volMult2 + volMult3 + volMult4 + volMult5) / i_basketSyms : i_basketSyms == 6 ? (volMult1 + volMult2 + volMult3 + volMult4 + volMult5 + volMult6) / i_basketSyms :
i_basketSyms == 7 ? (volMult1 + volMult2 + volMult3 + volMult4 + volMult5 + volMult6 + volMult7) / i_basketSyms : i_basketSyms == 8 ? (volMult1 + volMult2 + volMult3 + volMult4 + volMult5 + volMult6 + volMult7 + volMult8) / i_basketSyms :
i_basketSyms == 9 ? (volMult1 + volMult2 + volMult3 + volMult4 + volMult5 + volMult6 + volMult7 + volMult8 + volMult9) / i_basketSyms : i_basketSyms == 10 ? (volMult1 + volMult2 + volMult3 + volMult4 + volMult5 + volMult6 + volMult7 + volMult8 + volMult9 + volMult10) / i_basketSyms : na : na
//Forming average relative close
basketRange = i_basketSyms > 0 ? i_basketSyms == 1 ? rangePerc1 : i_basketSyms == 2 ? (rangePerc1 + rangePerc2) / i_basketSyms :
i_basketSyms == 3 ? (rangePerc1 + rangePerc2 + rangePerc3) / i_basketSyms : i_basketSyms == 4 ? (rangePerc1 + rangePerc2 + rangePerc3 + rangePerc4) / i_basketSyms :
i_basketSyms == 5 ? (rangePerc1 + rangePerc2 + rangePerc3 + rangePerc4 + rangePerc5) / i_basketSyms : i_basketSyms == 6 ? (rangePerc1 + rangePerc2 + rangePerc3 + rangePerc4 + rangePerc5 + rangePerc6) / i_basketSyms :
i_basketSyms == 7 ? (rangePerc1 + rangePerc2 + rangePerc3 + rangePerc4 + rangePerc5 + rangePerc6 + rangePerc7) / i_basketSyms : i_basketSyms == 8 ? (rangePerc1 + rangePerc2 + rangePerc3 + rangePerc4 + rangePerc5 + rangePerc6 + rangePerc7 + rangePerc8) / i_basketSyms :
i_basketSyms == 9 ? (rangePerc1 + rangePerc2 + rangePerc3 + rangePerc4 + rangePerc5 + rangePerc6 + rangePerc7 + rangePerc8 + rangePerc9) / i_basketSyms : i_basketSyms == 10 ? (rangePerc1 + rangePerc2 + rangePerc3 + rangePerc4 + rangePerc5 + rangePerc6 + rangePerc7 + rangePerc8 + rangePerc9 + rangePerc10) / i_basketSyms : na : na
// Plots
//Volatility, volume and relative close colors
volatilityCol = volMultRounded <= 1.00 ? color.from_gradient(volMultRounded, 0, 1.00, i_vol1, i_vol2) : volMultRounded >= 1.00 and volMultRounded <= 1.70 ? color.from_gradient(volMultRounded, 1.00, 1.70, i_vol2, i_vol3) : color.from_gradient(volMultRounded, 1.70, 2.4, i_vol3, i_vol4)
volumeCol = volumeMultRounded <= 1.00 ? color.from_gradient(volumeMultRounded, 0, 1.00, i_vol1, i_vol2) : volumeMultRounded >= 1.00 and volumeMultRounded <= 1.70 ? color.from_gradient(volumeMultRounded, 1.00, 1.70, i_vol2, i_vol3) : color.from_gradient(volumeMultRounded, 1.70, 2.4, i_vol3, i_vol4)
rangeCol = rangePos <= 0.25 ? color.from_gradient(rangePos, 0, 0.25, i_heavyBearRange, i_lightBearRange) :
rangePos >= 0.25 and rangePos <= 0.45 ? color.from_gradient(rangePos, 0.25, 0.45, i_lightBearRange, i_neutralRange) :
rangePos >= 0.55 and rangePos <= 0.75 ? color.from_gradient(rangePos, 0.55, 0.75, i_neutralRange, i_lightBullRange) :
rangePos >= 0.75 and rangePos <= 1.00 ? color.from_gradient(rangePos, 0.75, 1.00, i_lightBullRange, i_heavyBullRange) : i_neutralRange
//Label elements
n = "\n"
dot1 = " ●" + n + n
dot2 = " ●"
dot3 = n + n + " ●"
lookbackSymbol = i_lookback > 0 ? "↩︎ " : ""
vl = "|"
//Basket texts
avgText = i_textBool ? "" : "Avg. "
basketRangeText = i_basketSyms > 0 ? vl + avgText + str.tostring(math.round(basketRange, 0)) + "%" : ""
basketVolumeText = i_basketSyms > 0 ? vl + avgText + str.tostring(math.round(basketVolumeMult, 2)) + "x" : ""
basketVolText = i_basketSyms > 0 ? vl + avgText + str.tostring(math.round(basketVolMult, 2)) + "x" : ""
//Metric texts
rangeText = lookbackSymbol + (i_textBool ? " C: " : "Close: ") + str.tostring(rangePerc) + "%" + basketRangeText
volumeText = lookbackSymbol + (i_textBool ? " vE: " : "Volume: ") + str.tostring(volumeMultRounded) + "x" + basketVolumeText
volatilityText = lookbackSymbol + (i_textBool ? " vY: " : "Volatility: ") + str.tostring(volMultRounded) + "x" + basketVolText
//Metric text aggregated
labelText = " " + volumeText + n + "— " + rangeText + n + " " + volatilityText
//Initializing labels
var label posLabel = na
var label posLabel2 = na
var label posLabel3 = na
var label posLabel4 = na
//Label size
labelSize = i_labelSize == 1 ? size.tiny : i_labelSize == 2 ? size.small : i_labelSize == 3 ? size.normal : i_labelSize == 4 ? size.large : size.huge
//Populating labels, keeping label only on real-time bar
if i_labelBool
posLabel := label.new(x=bar_index+i_offset, y=close, xloc=xloc.bar_index, text=labelText[i_lookback], style=label.style_label_left, color=color.new(color.white, 100), textcolor=i_text, size=labelSize, textalign=text.align_left)
label.delete(posLabel[1])
if i_labelBool
posLabel2 := label.new(x=bar_index+i_offset, y=close, xloc=xloc.bar_index, text=dot1[i_lookback], style=label.style_label_left, color=color.new(color.white, 100), textcolor=volumeCol[i_lookback], size=labelSize, textalign=text.align_left)
label.delete(posLabel2[1])
if i_labelBool
posLabel3 := label.new(x=bar_index+i_offset, y=close, xloc=xloc.bar_index, text=dot2[i_lookback], style=label.style_label_left, color=color.new(color.white, 100), textcolor=rangeCol[i_lookback], size=labelSize, textalign=text.align_left)
label.delete(posLabel3[1])
if i_labelBool
posLabel4 := label.new(x=bar_index+i_offset, y=close, xloc=xloc.bar_index, text=dot3[i_lookback], style=label.style_label_left, color=color.new(color.white, 100), textcolor=volatilityCol[i_lookback], size=labelSize, textalign=text.align_left)
label.delete(posLabel4[1])
//Bar highlighter color
barcolor(i_highlightBool and allConds ? i_barCol : na)
//Initializing box
var box highlightBox = na
//Highlighting lookback bar with a box.
if i_lookback > 0
highlightBox := box.new(left=bar_index[i_lookback] - 1, top=high[i_lookback], right=bar_index[i_lookback] + 1, bottom=low[i_lookback], bgcolor=color.new(color.yellow, 80), border_color=color.new(color.white, 100))
box.delete(highlightBox[1])
// Table
//Table position and size
tablePosition = tablePos == "Top right" ? position.top_right : tablePos == "Bottom right" ? position.bottom_right : tablePos == "Bottom left" ? position.bottom_left : position.top_left
tableTextSize = tableSize == 1 ? size.tiny : tableSize == 2 ? size.small : tableSize == 3 ? size.normal : tableSize == 4 ? size.huge : size.large
//Initializing table
var metricTable = table.new(position = tablePosition, columns = 50, rows = 50, bgcolor = color.new(#191919, 100), border_width = 0, border_color=color.new(color.black, 100))
//Populating table
if i_tableBool
table.cell(table_id = metricTable, column = 0, row = 0, text = "●", text_color=rangeCol, text_halign=text.align_right, text_size=tableTextSize)
table.cell(table_id = metricTable, column = 0, row = 1, text = "●", text_color=volumeCol, text_halign=text.align_right, text_size=tableTextSize)
table.cell(table_id = metricTable, column = 0, row = 2, text = "●", text_color=volatilityCol, text_halign=text.align_right, text_size=tableTextSize)
table.cell(table_id = metricTable, column = 1, row = 0, text = rangeText[i_lookback], text_color=i_text, text_halign=text.align_left, text_size=tableTextSize)
table.cell(table_id = metricTable, column = 1, row = 1, text = volumeText[i_lookback], text_color=i_text, text_halign=text.align_left, text_size=tableTextSize)
table.cell(table_id = metricTable, column = 1, row = 2, text = volatilityText[i_lookback], text_color=i_text, text_halign=text.align_left, text_size=tableTextSize)
// Alerts
//Alert for specified bar metrics
alertcondition(allConds and (i_closeBool ? barstate.isconfirmed : na(close) == false), "Bar metric values within bracket range", "Bar metric values within bracket range detected.")
|
RSI Impact Heat Map [Trendoscope] | https://www.tradingview.com/script/zsmaLEyI-RSI-Impact-Heat-Map-Trendoscope/ | Trendoscope | https://www.tradingview.com/u/Trendoscope/ | 484 | 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("RSI Impact Heat Map [Trendoscope]", "RSIHM[Trendoscope]", overlay = false)
rsiSource = input.source(close, 'Source', inline='r', group='RSI')
rsiLength = input.int(14, '', 5, 200, 5, inline='r', group='RSI', tooltip = 'RSI configuration')
rsiTrigger = input.string('Crossover', 'Trigger', ['Crossover', 'Crossunder'], inline='rt', group = 'RSI')
rsiTriggerValue = input.int(70, '', 0, 100, 5, inline='rt', group = 'RSI', tooltip = 'Trigger for which we need to plot the impact')
impactDuration = input.int(20, 'Duration', 0, 500, 10, group='Impact', tooltip = 'Duration for which impact needs to be measured')
reference = input.string('ATR', 'Reference', ['ATR', 'Percentage'], group='Impact', tooltip='Reference on which the impact is measured')
matrixSize = input.int(50, 'Heat Map Size', 10, 90, 10, group='Display', tooltip = 'Number of rows, columns for heat map matrix')
outliersPercentile = input.int(95, 'Outliers Percentile', 50, 100, 5, group='Display', tooltip = 'Percentile to filter outliers. Value of 95 means, 95th percentile is considered as max displacement')
backgroundColor = input.color(color.rgb(0,0,0,0), 'Background', group='Display', tooltip = 'Background color')
heatmapColor = input.color(color.red, 'Heatmap', group='Display', tooltip = 'Heatmap color')
type Event
float xValue
float yValue
var array<Event> events = array.new<Event>()
rsi = ta.rsi(rsiSource, rsiLength)
trigger = rsiTrigger == 'Crossover' ? ta.crossover(rsi, rsiTriggerValue) : ta.crossunder(rsi, rsiTriggerValue)
atr = ta.atr(rsiLength)
highest = ta.highest(impactDuration-1)
lowest = ta.lowest(impactDuration-1)
var array<float> displacements = array.new<float>()
if(trigger[impactDuration])
price = close[impactDuration]
positiveDisplacement = math.abs(highest-price)
negativeDisplacement = math.abs(price-lowest)
xValue = reference == 'ATR'? positiveDisplacement/atr[impactDuration] : reference == 'Percentage' ? positiveDisplacement/price : positiveDisplacement
yValue = reference == "ATR"? negativeDisplacement/atr[impactDuration] : reference == 'Percentage' ? negativeDisplacement/price : negativeDisplacement
array.push(displacements, xValue)
array.push(displacements, yValue)
Event event = Event.new(xValue, yValue)
array.push(events, event)
if(barstate.isfirst)
var titleTable = table.new(position.top_center, 2, 3, color.maroon, color.maroon, 1, color.maroon, 1)
title = 'Impact of RSI('+str.tostring(rsiLength)+') '+rsiTrigger+' '+str.tostring(rsiTriggerValue)+ ' after '+str.tostring(impactDuration)+ ' bars measured in terms of '+reference
table.cell(titleTable, 0, 0, title, text_color = color.white)
if(barstate.islast)
matrix<int> counts = matrix.new<int>(matrixSize+1, matrixSize+1, 0)
maxRange = array.percentile_linear_interpolation(displacements, outliersPercentile)
for event in events
xIndex = math.min(int(event.xValue*matrixSize/maxRange), matrixSize)
yIndex = matrixSize - math.min(int(event.yValue*matrixSize/maxRange), matrixSize)
matrix.set(counts, xIndex, yIndex, matrix.get(counts, xIndex, yIndex)+1)
var heatmap = table.new(position.middle_center, matrixSize+1, matrixSize+1, backgroundColor, color.yellow, 1, backgroundColor, 0)
table.clear(heatmap, 0, 0, matrixSize, matrixSize)
maxCount = matrix.max(counts)
totalCount = array.size(events)
sums = array.new<int>(4,0)
for [i, columns] in counts
for [j, count] in columns
countPercent = int(count*90/maxCount)
sumIndex = 2*(i < ((matrixSize+1)/2) ? 0 : 1) + (j < ((matrixSize+1)/2)? 0: 1)
array.set(sums, sumIndex, array.get(sums, sumIndex)+count)
xRange = 'Positive Displaecment : ' + (reference == 'Percentage'? str.tostring(maxRange*i*100/matrixSize, format.percent) : (str.tostring(maxRange*i/matrixSize, format.mintick) + 'X'))
+ ' - '+ ((i==matrixSize)? '' :
(reference == 'Percentage'? str.tostring(maxRange*(i+1)*100/matrixSize, format.percent) : (str.tostring(maxRange*(i+1)/matrixSize, format.mintick) + 'X')))
yRange = 'Negative Displacement : ' + (reference == 'Percentage'? str.tostring(maxRange*(matrixSize-j)*100/matrixSize, format.percent) : (str.tostring(maxRange*(matrixSize-j)/matrixSize, format.mintick) + 'X'))
+ ' - '+ ((j==matrixSize)? '' :
(reference == 'Percentage'? str.tostring(maxRange*(matrixSize-j+1)*100/matrixSize, format.percent) : (str.tostring(maxRange*(matrixSize-j+1)/matrixSize, format.mintick) + 'X')))
tooltip = 'Count '+str.tostring(count)+'/'+str.tostring(totalCount)+'\n'+xRange+'\n'+yRange+'\n('+str.tostring(i)+','+str.tostring(j)+')'
table.cell(heatmap, i, j, '', width=1, height = 1, text_color=color.yellow, bgcolor = color.new(heatmapColor, countPercent==0? 100 : 90-countPercent), text_size = size.tiny, tooltip = tooltip)
var positions = array.from(position.top_left, position.bottom_left, position.top_right, position.bottom_right)
for [i, sum] in sums
tab = table.new(array.get(positions, i), 1,1, color.teal, color.teal, 1, color.teal, 1)
table.cell(tab, 0, 0, str.tostring(sum), text_color = color.white, text_size = size.large)
|
Support Resistance with Breaks and Retests | https://www.tradingview.com/script/Xeeko6TV-Support-Resistance-with-Breaks-and-Retests/ | HoanGhetti | https://www.tradingview.com/u/HoanGhetti/ | 2,445 | 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/
// © HoanGhetti
//@version=5
indicator("Breaks and Retests [HG]", overlay = true, max_boxes_count = 500, max_labels_count = 500)
g_sr = 'Support and Resistance'
g_c = 'Conditions'
g_st = 'Styling'
t_r = 'Bar Confirmation: Generates alerts when candle closes. (1 Candle Later) \n\nHigh & Low: By default, the Break & Retest system uses the current close value to determine a condition, selecting High & Low will make the script utilize these two values instead of the close value. In return, the script won\'t repaint and will yield different results.'
t_rv = 'Whenever a potential retest is detected, the indicator knows that a retest is about to happen. In that given situation, this input grants the ability to raise the limit on how many bars are allowed to be actively checked while a potential retest event is active.\n\nExample, if you see the potential retest label, how many bars do you want that potential retest label to be active for to eventually confirm a retest? This system was implemented to prevent retest alerts from going off 10+ bars later from the potential retest point leading to inaccurate results.'
input_lookback = input.int(defval = 20, title = 'Lookback Range', minval = 1, tooltip = 'How many bars for a pivot event to occur.', group = g_sr)
input_retSince = input.int(defval = 2, title = 'Bars Since Breakout', minval = 1, tooltip = 'How many bars since breakout in order to detect a retest.', group = g_sr)
input_retValid = input.int(defval = 2, title = 'Retest Detection Limiter', minval = 1, tooltip = t_rv, group = g_sr)
input_breakout = input.bool(defval = true, title = 'Breakouts', group = g_c)
input_retest = input.bool(defval = true, title = 'Retests', group = g_c)
input_repType = input.string(defval = 'On', title = 'Repainting', options = ['On', 'Off: Candle Confirmation', 'Off: High & Low'], tooltip = t_r, group = g_c)
input_outL = input.string(defval = line.style_dotted, title = 'Outline', group = g_st, options = [line.style_dotted, line.style_dashed, line.style_solid])
input_extend = input.string(defval = extend.none, title = 'Extend', group = g_st, options = [extend.none, extend.right, extend.left, extend.both])
input_labelType = input.string(defval = 'Full', title = 'Label Type', options = ['Full', 'Simple'], group = g_st)
input_labelSize = input.string(defval = size.small, title = 'Label Size', options = [size.tiny, size.small, size.normal, size.large, size.huge], group = g_st)
input_plColor = input.color(defval = color.red, title = 'Support', inline = 'Color', group = g_st)
input_phColor = input.color(defval = #089981, title = 'Resistance', inline = 'Color', group = g_st)
input_override = input.bool(defval = false, title = 'Override Text Color ', inline = 'Override', group = g_st)
input_textColor = input.color(defval = color.white, title = '', inline = 'Override', group = g_st)
bb = input_lookback
rTon = input_repType == 'On'
rTcc = input_repType == 'Off: Candle Confirmation'
rThv = input_repType == 'Off: High & Low'
breakText = input_labelType == 'Simple' ? 'Br' : 'Break'
// Pivot Instance
pl = fixnan(ta.pivotlow(low, bb, bb))
ph = fixnan(ta.pivothigh(high, bb, bb))
// Box Height
s_yLoc = low[bb + 1] > low[bb - 1] ? low[bb - 1] : low[bb + 1]
r_yLoc = high[bb + 1] > high[bb - 1] ? high[bb + 1] : high[bb - 1]
//-----------------------------------------------------------------------------
// Functions
//-----------------------------------------------------------------------------
drawBox(condition, y1, y2, color) =>
var box drawBox = na
if condition
box.set_right(drawBox, bar_index - bb)
drawBox.set_extend(extend.none)
drawBox := box.new(bar_index - bb, y1, bar_index, y2, color, bgcolor = color.new(color, 90), border_style = input_outL, extend = input_extend)
[drawBox]
updateBox(box) =>
if barstate.isconfirmed
box.set_right(box, bar_index + 5)
breakLabel(y, color, style, textform) => label.new(bar_index, y, textform, textcolor = input_override ? input_textColor : color, style = style, color = color.new(color, 50), size = input_labelSize)
retestCondition(breakout, condition) => ta.barssince(na(breakout)) > input_retSince and condition
repaint(c1, c2, c3) => rTon ? c1 : rThv ? c2 : rTcc ? c3 : na
//-----------------------------------------------------------------------------
// Draw and Update Boxes
//-----------------------------------------------------------------------------
[sBox] = drawBox(ta.change(pl), s_yLoc, pl, input_plColor)
[rBox] = drawBox(ta.change(ph), ph, r_yLoc, input_phColor)
sTop = box.get_top(sBox), rTop = box.get_top(rBox)
sBot = box.get_bottom(sBox), rBot = box.get_bottom(rBox)
updateBox(sBox), updateBox(rBox)
//-----------------------------------------------------------------------------
// Breakout Event
//-----------------------------------------------------------------------------
var bool sBreak = na
var bool rBreak = na
cu = repaint(ta.crossunder(close, box.get_bottom(sBox)), ta.crossunder(low, box.get_bottom(sBox)), ta.crossunder(close, box.get_bottom(sBox)) and barstate.isconfirmed)
co = repaint(ta.crossover(close, box.get_top(rBox)), ta.crossover(high, box.get_top(rBox)), ta.crossover(close, box.get_top(rBox)) and barstate.isconfirmed)
switch
cu and na(sBreak) =>
sBreak := true
if input_breakout
breakLabel(sBot, input_plColor, label.style_label_upper_right, breakText)
co and na(rBreak) =>
rBreak := true
if input_breakout
breakLabel(rTop, input_phColor, label.style_label_lower_right, breakText)
if ta.change(pl)
if na(sBreak)
box.delete(sBox[1])
sBreak := na
if ta.change(ph)
if na(rBreak)
box.delete(rBox[1])
rBreak := na
//-----------------------------------------------------------------------------
// Retest Event
//-----------------------------------------------------------------------------
s1 = retestCondition(sBreak, high >= sTop and close <= sBot) // High is GOET top sBox value and the close price is LOET the bottom sBox value.
s2 = retestCondition(sBreak, high >= sTop and close >= sBot and close <= sTop) // High is GOET top sBox value and close is GOET the bottom sBox value and closing price is LOET the top sBox value.
s3 = retestCondition(sBreak, high >= sBot and high <= sTop) // High is in between the sBox.
s4 = retestCondition(sBreak, high >= sBot and high <= sTop and close < sBot) // High is in between the sBox, and the closing price is below.
r1 = retestCondition(rBreak, low <= rBot and close >= rTop) // Low is LOET bottom rBox value and close is GOET the top sBox value
r2 = retestCondition(rBreak, low <= rBot and close <= rTop and close >= rBot) // Low is LOET bottom rBox value and close is LOET the top sBox value and closing price is GOET the bottom rBox value.
r3 = retestCondition(rBreak, low <= rTop and low >= rBot) // Low is in between the rBox.
r4 = retestCondition(rBreak, low <= rTop and low >= rBot and close > rTop) // Low is in between the rBox, and the closing price is above.
retestEvent(c1, c2, c3, c4, y1, y2, col, style, pType) =>
if input_retest
var bool retOccurred = na
retActive = c1 or c2 or c3 or c4
retEvent = retActive and not retActive[1]
retValue = ta.valuewhen(retEvent, y1, 0)
if pType == 'ph' ? y2 < ta.valuewhen(retEvent, y2, 0) : y2 > ta.valuewhen(retEvent, y2, 0)
retEvent := retActive
// Must be reassigned here just in case the above if statement triggers.
retValue := ta.valuewhen(retEvent, y1, 0)
retSince = ta.barssince(retEvent)
var retLabel = array.new<label>()
if retEvent
retOccurred := na
array.push(retLabel, label.new(bar_index - retSince, y2[retSince], text = input_labelType == 'Simple' ? 'P. Re' : 'Potential Retest', color = color.new(col, 50), style = style, textcolor = input_override ? input_textColor : col, size = input_labelSize))
if array.size(retLabel) == 2
label.delete(array.first(retLabel))
array.shift(retLabel)
retConditions = pType == 'ph' ? repaint(close >= retValue, high >= retValue, close >= retValue and barstate.isconfirmed) : repaint(close <= retValue, low <= retValue, close <= retValue and barstate.isconfirmed)
retValid = ta.barssince(retEvent) > 0 and ta.barssince(retEvent) <= input_retValid and retConditions and not retOccurred
if retValid
label.new(bar_index - retSince, y2[retSince], text = input_labelType == 'Simple' ? 'Re' : 'Retest', color = color.new(col, 50), style = style, textcolor = input_override ? input_textColor : col, size = input_labelSize)
retOccurred := true
if retValid or ta.barssince(retEvent) > input_retValid
label.delete(array.first(retLabel))
if pType == 'ph' and ta.change(ph) and retOccurred
box.set_right(rBox[1], bar_index - retSince)
retOccurred := na
if pType == 'pl' and ta.change(pl) and retOccurred
box.set_right(sBox[1], bar_index - retSince)
retOccurred := na
[retValid, retEvent, retValue]
[rRetValid, rRetEvent] = retestEvent(r1, r2, r3, r4, high, low, input_phColor, label.style_label_upper_left, 'ph')
[sRetValid, sRetEvent] = retestEvent(s1, s2, s3, s4, low, high, input_plColor, label.style_label_lower_left, 'pl')
//-----------------------------------------------------------------------------
// Alerts
//-----------------------------------------------------------------------------
alertcondition(ta.change(pl), 'New Support Level')
alertcondition(ta.change(ph), 'New Resistance Level')
alertcondition(ta.barssince(na(sBreak)) == 1, 'Support Breakout')
alertcondition(ta.barssince(na(rBreak)) == 1, 'Resistance Breakout')
alertcondition(sRetValid, 'Support Retest')
alertcondition(sRetEvent, 'Potential Support Retest')
alertcondition(rRetValid, 'Resistance Retest')
alertcondition(rRetEvent, 'Potential Resistance Retest')
AllAlerts(condition, message) =>
if condition
alert(message)
AllAlerts(ta.change(pl), 'New Support Level')
AllAlerts(ta.change(ph), 'New Resistance Level')
AllAlerts(ta.barssince(na(sBreak)) == 1, 'Support Breakout')
AllAlerts(ta.barssince(na(rBreak)) == 1, 'Resistance Breakout')
AllAlerts(sRetValid, 'Support Retest')
AllAlerts(sRetEvent, 'Potential Support Retest')
AllAlerts(rRetValid, 'Resistance Retest')
AllAlerts(rRetEvent, 'Potential Resistance Retest')
|
Hurst Spectral Analysis SwamiChart | https://www.tradingview.com/script/TNLh236f-Hurst-Spectral-Analysis-SwamiChart/ | BarefootJoey | https://www.tradingview.com/u/BarefootJoey/ | 65 | 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/
// © BarefootJoey
// ██████████████████████████████████████████████████████████████████████
// █▄─▄─▀██▀▄─██▄─▄▄▀█▄─▄▄─█▄─▄▄─█─▄▄─█─▄▄─█─▄─▄─███▄─▄█─▄▄─█▄─▄▄─█▄─█─▄█
// ██─▄─▀██─▀─███─▄─▄██─▄█▀██─▄███─██─█─██─███─███─▄█─██─██─██─▄█▀██▄─▄██
// █▄▄▄▄██▄▄█▄▄█▄▄█▄▄█▄▄▄▄▄█▄▄▄███▄▄▄▄█▄▄▄▄██▄▄▄██▄▄▄███▄▄▄▄█▄▄▄▄▄██▄▄▄██
//@version=5
indicator("Hurst Spectral Analysis SwamiChart", overlay=false)
var color brightgreen = #00ff0a
var color brightred = #ff1100
grbps = "Bandpass Settings"
grscs = "SwamiChart Settings"
//-------------------------------Inputs-------------------------------//
source = input(close, 'Bandpass Source', group=grbps)
bandWidth = input.float(0.025, 'Bandwidth', minval=0.0, maxval=1.0, group=grbps)
periodBP = input.int(40, 'Base Period', minval=2, group=grbps)
periodStep = input.int(1, 'Step', minval=1, group=grbps)
hm_type = "Amplitude"
bull_col = input.color(brightgreen, group=grscs)
bear_col = input.color(brightred, group=grscs)
width = input.int(2, 'Linewidth', minval=1, maxval=4, group=grscs)
text_size = input.session('Normal', "Text Size", options=["Tiny","Small","Normal","Large"], group=grscs)
//-------------------------------Functions & Calculations-------------------------------//
// @TMPascoe found & offered this bandpass by @HPotter found here https://www.tradingview.com/script/A1jhw5fG-Bandpass-Filter/
// @BarefootJoey turned the code into a function and made it accept float Period
bpf(Series, float Period, Delta) =>
float tmpbpf = na
var beta = math.cos(3.14 * (360 / Period) / 180)
var gamma = 1 / math.cos(3.14 * (720 * Delta / Period) / 180)
var alpha = gamma - math.sqrt(gamma * gamma - 1)
tmpbpf := 0.5 * (1 - alpha) * (Series - Series[2]) + beta * (1 + alpha) * nz(tmpbpf[1]) - alpha * nz(tmpbpf[2])
// Individual Bandpass Filters
bpf1 = bpf(source, periodBP + (periodStep*0), bandWidth)
bpf2 = bpf(source, periodBP + (periodStep*1), bandWidth)
bpf3 = bpf(source, periodBP + (periodStep*2), bandWidth)
bpf4 = bpf(source, periodBP + (periodStep*3), bandWidth)
bpf5 = bpf(source, periodBP + (periodStep*4), bandWidth)
bpf6 = bpf(source, periodBP + (periodStep*5), bandWidth)
bpf7 = bpf(source, periodBP + (periodStep*6), bandWidth)
bpf8 = bpf(source, periodBP + (periodStep*7), bandWidth)
bpf9 = bpf(source, periodBP + (periodStep*8), bandWidth)
bpf10 = bpf(source, periodBP + (periodStep*9), bandWidth)
bpf11 = bpf(source, periodBP + (periodStep*10), bandWidth)
bpf12 = bpf(source, periodBP + (periodStep*11), bandWidth)
bpf13 = bpf(source, periodBP + (periodStep*12), bandWidth)
bpf14 = bpf(source, periodBP + (periodStep*13), bandWidth)
bpf15 = bpf(source, periodBP + (periodStep*14), bandWidth)
bpf16 = bpf(source, periodBP + (periodStep*15), bandWidth)
bpf17 = bpf(source, periodBP + (periodStep*16), bandWidth)
bpf18 = bpf(source, periodBP + (periodStep*17), bandWidth)
bpf19 = bpf(source, periodBP + (periodStep*18), bandWidth)
bpf20 = bpf(source, periodBP + (periodStep*19), bandWidth)
bpf21 = bpf(source, periodBP + (periodStep*20), bandWidth)
bpf22 = bpf(source, periodBP + (periodStep*21), bandWidth)
bpf23 = bpf(source, periodBP + (periodStep*22), bandWidth)
bpf24 = bpf(source, periodBP + (periodStep*23), bandWidth)
bpf25 = bpf(source, periodBP + (periodStep*24), bandWidth)
bpf26 = bpf(source, periodBP + (periodStep*25), bandWidth)
bpf27 = bpf(source, periodBP + (periodStep*26), bandWidth)
bpf28 = bpf(source, periodBP + (periodStep*27), bandWidth)
bpf29 = bpf(source, periodBP + (periodStep*28), bandWidth)
bpf30 = bpf(source, periodBP + (periodStep*29), bandWidth)
bpf31 = bpf(source, periodBP + (periodStep*30), bandWidth)
bpf32 = bpf(source, periodBP + (periodStep*31), bandWidth)
// Hi/Lo (Amplitude) Gradient
grad1 = color.from_gradient(bpf1, ta.lowest(bpf1,periodBP +(periodStep*0)), ta.highest(bpf1,periodBP +(periodStep*0)), bull_col, bear_col)
grad2 = color.from_gradient(bpf2, ta.lowest(bpf2,periodBP +(periodStep*1)), ta.highest(bpf2,periodBP +(periodStep*1)), bull_col, bear_col)
grad3 = color.from_gradient(bpf3, ta.lowest(bpf3,periodBP +(periodStep*2)), ta.highest(bpf3,periodBP +(periodStep*2)), bull_col, bear_col)
grad4 = color.from_gradient(bpf4, ta.lowest(bpf4,periodBP +(periodStep*3)), ta.highest(bpf4,periodBP +(periodStep*3)), bull_col, bear_col)
grad5 = color.from_gradient(bpf5, ta.lowest(bpf5,periodBP +(periodStep*4)), ta.highest(bpf5,periodBP +(periodStep*4)), bull_col, bear_col)
grad6 = color.from_gradient(bpf6, ta.lowest(bpf6,periodBP +(periodStep*5)), ta.highest(bpf6,periodBP +(periodStep*5)), bull_col, bear_col)
grad7 = color.from_gradient(bpf7, ta.lowest(bpf7,periodBP +(periodStep*6)), ta.highest(bpf7,periodBP +(periodStep*6)), bull_col, bear_col)
grad8 = color.from_gradient(bpf8, ta.lowest(bpf8,periodBP +(periodStep*7)), ta.highest(bpf8,periodBP +(periodStep*7)), bull_col, bear_col)
grad9 = color.from_gradient(bpf9, ta.lowest(bpf9,periodBP +(periodStep*8)), ta.highest(bpf9,periodBP +(periodStep*8)), bull_col, bear_col)
grad10 = color.from_gradient(bpf10, ta.lowest(bpf10,periodBP +(periodStep*9)), ta.highest(bpf10,periodBP +(periodStep*9)), bull_col, bear_col)
grad11 = color.from_gradient(bpf11, ta.lowest(bpf11,periodBP +(periodStep*10)), ta.highest(bpf11,periodBP +(periodStep*10)), bull_col, bear_col)
grad12 = color.from_gradient(bpf12, ta.lowest(bpf12,periodBP +(periodStep*11)), ta.highest(bpf12,periodBP +(periodStep*11)), bull_col, bear_col)
grad13 = color.from_gradient(bpf13, ta.lowest(bpf13,periodBP +(periodStep*12)), ta.highest(bpf13,periodBP +(periodStep*12)), bull_col, bear_col)
grad14 = color.from_gradient(bpf14, ta.lowest(bpf14,periodBP +(periodStep*13)), ta.highest(bpf14,periodBP +(periodStep*13)), bull_col, bear_col)
grad15 = color.from_gradient(bpf15, ta.lowest(bpf15,periodBP +(periodStep*14)), ta.highest(bpf15,periodBP +(periodStep*14)), bull_col, bear_col)
grad16 = color.from_gradient(bpf16, ta.lowest(bpf16,periodBP +(periodStep*15)), ta.highest(bpf16,periodBP +(periodStep*15)), bull_col, bear_col)
grad17 = color.from_gradient(bpf17, ta.lowest(bpf17,periodBP +(periodStep*16)), ta.highest(bpf17,periodBP +(periodStep*16)), bull_col, bear_col)
grad18 = color.from_gradient(bpf18, ta.lowest(bpf18,periodBP +(periodStep*17)), ta.highest(bpf18,periodBP +(periodStep*17)), bull_col, bear_col)
grad19 = color.from_gradient(bpf19, ta.lowest(bpf19,periodBP +(periodStep*18)), ta.highest(bpf19,periodBP +(periodStep*18)), bull_col, bear_col)
grad20 = color.from_gradient(bpf20, ta.lowest(bpf20,periodBP +(periodStep*19)), ta.highest(bpf20,periodBP +(periodStep*19)), bull_col, bear_col)
grad21 = color.from_gradient(bpf21, ta.lowest(bpf21,periodBP +(periodStep*20)), ta.highest(bpf21,periodBP +(periodStep*20)), bull_col, bear_col)
grad22 = color.from_gradient(bpf22, ta.lowest(bpf22,periodBP +(periodStep*21)), ta.highest(bpf22,periodBP +(periodStep*21)), bull_col, bear_col)
grad23 = color.from_gradient(bpf23, ta.lowest(bpf23,periodBP +(periodStep*22)), ta.highest(bpf23,periodBP +(periodStep*22)), bull_col, bear_col)
grad24 = color.from_gradient(bpf24, ta.lowest(bpf24,periodBP +(periodStep*23)), ta.highest(bpf24,periodBP +(periodStep*23)), bull_col, bear_col)
grad25 = color.from_gradient(bpf25, ta.lowest(bpf25,periodBP +(periodStep*24)), ta.highest(bpf25,periodBP +(periodStep*24)), bull_col, bear_col)
grad26 = color.from_gradient(bpf26, ta.lowest(bpf26,periodBP +(periodStep*25)), ta.highest(bpf26,periodBP +(periodStep*25)), bull_col, bear_col)
grad27 = color.from_gradient(bpf27, ta.lowest(bpf27,periodBP +(periodStep*26)), ta.highest(bpf27,periodBP +(periodStep*26)), bull_col, bear_col)
grad28 = color.from_gradient(bpf28, ta.lowest(bpf28,periodBP +(periodStep*27)), ta.highest(bpf28,periodBP +(periodStep*27)), bull_col, bear_col)
grad29 = color.from_gradient(bpf29, ta.lowest(bpf29,periodBP +(periodStep*28)), ta.highest(bpf29,periodBP +(periodStep*28)), bull_col, bear_col)
grad30 = color.from_gradient(bpf30, ta.lowest(bpf30,periodBP +(periodStep*29)), ta.highest(bpf30,periodBP +(periodStep*29)), bull_col, bear_col)
grad31 = color.from_gradient(bpf31, ta.lowest(bpf31,periodBP +(periodStep*30)), ta.highest(bpf31,periodBP +(periodStep*30)), bull_col, bear_col)
grad32 = color.from_gradient(bpf32, ta.lowest(bpf32,periodBP +(periodStep*31)), ta.highest(bpf32,periodBP +(periodStep*31)), bull_col, bear_col)
plot(0*width, color=grad1, linewidth=width, editable=false)
plot(1*width, color=grad2, linewidth=width, editable=false)
plot(2*width, color=grad3, linewidth=width, editable=false)
plot(3*width, color=grad4, linewidth=width, editable=false)
plot(4*width, color=grad5, linewidth=width, editable=false)
plot(5*width, color=grad6, linewidth=width, editable=false)
plot(6*width, color=grad7, linewidth=width, editable=false)
plot(7*width, color=grad8, linewidth=width, editable=false)
plot(8*width, color=grad9, linewidth=width, editable=false)
plot(9*width, color=grad10, linewidth=width, editable=false)
plot(10*width, color=grad11, linewidth=width, editable=false)
plot(11*width, color=grad12, linewidth=width, editable=false)
plot(12*width, color=grad13, linewidth=width, editable=false)
plot(13*width, color=grad14, linewidth=width, editable=false)
plot(14*width, color=grad15, linewidth=width, editable=false)
plot(15*width, color=grad16, linewidth=width, editable=false)
plot(16*width, color=grad17, linewidth=width, editable=false)
plot(17*width, color=grad18, linewidth=width, editable=false)
plot(18*width, color=grad19, linewidth=width, editable=false)
plot(19*width, color=grad20, linewidth=width, editable=false)
plot(20*width, color=grad21, linewidth=width, editable=false)
plot(21*width, color=grad22, linewidth=width, editable=false)
plot(22*width, color=grad23, linewidth=width, editable=false)
plot(23*width, color=grad24, linewidth=width, editable=false)
plot(24*width, color=grad25, linewidth=width, editable=false)
plot(25*width, color=grad26, linewidth=width, editable=false)
plot(26*width, color=grad27, linewidth=width, editable=false)
plot(27*width, color=grad28, linewidth=width, editable=false)
plot(28*width, color=grad29, linewidth=width, editable=false)
plot(29*width, color=grad30, linewidth=width, editable=false)
plot(30*width, color=grad31, linewidth=width, editable=false)
plot(31*width, color=grad32, linewidth=width, editable=false)
var label_text_size = text_size == 'Tiny' ? size.tiny :
text_size == 'Small' ? size.small :
text_size == 'Normal' ? size.normal : size.large
var label l1 = na
var label l2 = na
var label l3 = na
if barstate.islast
l1 := label.new(bar_index, y=0*width, text=str.tostring(periodBP, '#'), size=label_text_size, style=label.style_label_left, color=color.new(color.white,100), textcolor=color.new(grad1,0))
l2 := label.new(bar_index, y=15*width, text=str.tostring(periodBP + (periodStep*15), '#'), size=label_text_size, style=label.style_label_left, color=color.new(color.white,100), textcolor=color.new(grad16,0))
l3 := label.new(bar_index, y=31*width, text=str.tostring(periodBP + (periodStep*39), '#'), size=label_text_size, style=label.style_label_left, color=color.new(color.white,100), textcolor=color.new(grad32,0))
label.delete(l1[1])
label.delete(l2[1])
label.delete(l3[1])
// EoS made w/ ❤ by @BarefootJoey ✌💗📈 |
Fibonacci Levels Based on Supertrend [By MUQWISHI] | https://www.tradingview.com/script/ziw9l3lF-Fibonacci-Levels-Based-on-Supertrend-By-MUQWISHI/ | MUQWISHI | https://www.tradingview.com/u/MUQWISHI/ | 827 | 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/
// © MUQWISHI
//@version=5
indicator("Supertrend-Fib", overlay = true, max_lines_count = 500, max_labels_count = 500)
// |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
// | INPUT |
// |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
// SuperTrend
supAtr = input.int(10, "ATR Length", 1, group = "Supertrend", inline = "1")
factor = input.float(3.0, " Factor", group = "Supertrend", inline = "1")
pltChk = input.bool(true, "Show Supertrend Line?", group = "Supertrend", inline = "2")
upCol = input.color(color.green, " ", group = "Supertrend", inline = "2")
dnCol = input.color(color.red, "", group = "Supertrend", inline = "2")
// Table Style
tablePos = input.string("Top Right", "RunUp Statistics Table Location ",
["Hide", "Top Right" , "Middle Right" , "Bottom Right" ,
"Top Center", "Middle Center" , "Bottom Center",
"Top Left" , "Middle Left" , "Bottom Left" ], inline = "1", group = "Fibonacci Run-Up Historical Statistics Table")
tBgCol = input.color(#696969, "Title", inline = "2", group = "Fibonacci Run-Up Historical Statistics Table")
cBgCol = input.color(#A9A9A9, " Cell", inline = "2", group = "Fibonacci Run-Up Historical Statistics Table")
txtCol = input.color(#ffffff, " Text", inline = "2", group = "Fibonacci Run-Up Historical Statistics Table")
// Line Style
linExt = input.string("None Extend", "Lines ",
["Hide", "Right Extend", "Left Extend", "Both Extend", "None Extend"], group = "Line & Label Style", inline = "line")
linSty = input.string("________", "",
["________", "-----------", "..........."], group = "Line & Label Style", inline = "line")
linSiz = input.int(2, "", 1, tooltip = "Line Extend | Line Style | Line Size", group = "Line & Label Style", inline = "line")
// Label Style
lblPos = input.string("Right", "Labels", ["Hide", "Right"], group = "Line & Label Style", inline = "label")
lblSty = input.string("Percent", "",
["Percent", "Value", "Price", "Percent & Price", "Value & Price"], group = "Line & Label Style", inline = "label")
lblSiz = input.string("Small", "",
["Auto", "Huge", "Large", "Normal", "Small", "Tiny"], group = "Line & Label Style", inline = "label",
tooltip = "Label Position | Label Style | Label Size")
// Fibonacci
lastSet = input.bool(true, "Apply Fibonacci Levels to ONLY Last Supertrend Direction", group = "Fibonacci Levels")
confrim = input.bool(true, "Apply Fibonacci Levels After Confirmed Signal", group = "Fibonacci Levels")
bgTrans = input.int(85, "Background Transparency", 0, 100, group = "Fibonacci Levels")
lnTrans = input.int(50, "Line Transparency ", 0, 100, group = "Fibonacci Levels")
trndChk = input.bool(true, "Show Trend Line", group = "Fibonacci Levels", inline = "0")
trndCol = input.color(color.new(#64b5f6, 50), " ", group = "Fibonacci Levels", inline = "0")
shw01 = input.bool(true, "", group = "Fibonacci Levels", inline = "Level00")
val01 = input.float(0.0, "", group = "Fibonacci Levels", inline = "Level00")
col01 = input.color(#787b86, "", group = "Fibonacci Levels", inline = "Level00")
shw02 = input.bool(true, "", group = "Fibonacci Levels", inline = "Level00")
val02 = input.float(0.236, "", group = "Fibonacci Levels", inline = "Level00")
col02 = input.color(#f44336,"", group = "Fibonacci Levels", inline = "Level00")
shw03 = input.bool(true, "", group = "Fibonacci Levels", inline = "Level01")
val03 = input.float(0.382, "", group = "Fibonacci Levels", inline = "Level01")
col03 = input.color(#81c784, "", group = "Fibonacci Levels", inline = "Level01")
shw04 = input.bool(true, "", group = "Fibonacci Levels", inline = "Level01")
val04 = input.float(0.5, "", group = "Fibonacci Levels", inline = "Level01")
col04 = input.color(#4caf50, "", group = "Fibonacci Levels", inline = "Level01")
shw05 = input.bool(true, "", group = "Fibonacci Levels", inline = "Level02")
val05 = input.float(0.618, "", group = "Fibonacci Levels", inline = "Level02")
col05 = input.color(#009688, "", group = "Fibonacci Levels", inline = "Level02")
shw06 = input.bool(true, "", group = "Fibonacci Levels", inline = "Level02")
val06 = input.float(0.786, "", group = "Fibonacci Levels", inline = "Level02")
col06 = input.color(#009688, "", group = "Fibonacci Levels", inline = "Level02")
shw07 = input.bool(true, "", group = "Fibonacci Levels", inline = "Level03")
val07 = input.float(1.0, "", group = "Fibonacci Levels", inline = "Level03")
col07 = input.color(#64b5f6, "", group = "Fibonacci Levels", inline = "Level03")
shw08 = input.bool(true, "", group = "Fibonacci Levels", inline = "Level03")
val08 = input.float(1.618, "", group = "Fibonacci Levels", inline = "Level03")
col08 = input.color(#da7d31, "", group = "Fibonacci Levels", inline = "Level03")
shw09 = input.bool(true, "", group = "Fibonacci Levels", inline = "Level04")
val09 = input.float(2.1618, "", group = "Fibonacci Levels", inline = "Level04")
col09 = input.color(#81c784, "", group = "Fibonacci Levels", inline = "Level04")
shw10 = input.bool(true, "", group = "Fibonacci Levels", inline = "Level04")
val10 = input.float(3.618, "", group = "Fibonacci Levels", inline = "Level04")
col10 = input.color(#f44336, "", group = "Fibonacci Levels", inline = "Level04")
shw11 = input.bool(true, "", group = "Fibonacci Levels", inline = "Level05")
val11 = input.float(4.236, "", group = "Fibonacci Levels", inline = "Level05")
col11 = input.color(#809ef0, "", group = "Fibonacci Levels", inline = "Level05")
shw12 = input.bool(false, "", group = "Fibonacci Levels", inline = "Level05")
val12 = input.float(1.272, "", group = "Fibonacci Levels", inline = "Level05")
col12 = input.color(#2962ff, "", group = "Fibonacci Levels", inline = "Level05")
shw13 = input.bool(false, "", group = "Fibonacci Levels", inline = "Level06")
val13 = input.float(1.414, "", group = "Fibonacci Levels", inline = "Level06")
col13 = input.color(#e97527, "", group = "Fibonacci Levels", inline = "Level06")
shw14 = input.bool(false, "", group = "Fibonacci Levels", inline = "Level06")
val14 = input.float(2.272, "", group = "Fibonacci Levels", inline = "Level06")
col14 = input.color(#f44336, "", group = "Fibonacci Levels", inline = "Level06")
shw15 = input.bool(false, "", group = "Fibonacci Levels", inline = "Level07")
val15 = input.float(2.414, "", group = "Fibonacci Levels", inline = "Level07")
col15 = input.color(#9c27b0, "", group = "Fibonacci Levels", inline = "Level07")
shw16 = input.bool(false, "", group = "Fibonacci Levels", inline = "Level07")
val16 = input.float(2.0, "", group = "Fibonacci Levels", inline = "Level07")
col16 = input.color(#b54df1, "", group = "Fibonacci Levels", inline = "Level07")
shw17 = input.bool(false, "", group = "Fibonacci Levels", inline = "Level08")
val17 = input.float(3.0, "", group = "Fibonacci Levels", inline = "Level08")
col17 = input.color(#e91e63, "", group = "Fibonacci Levels", inline = "Level08")
shw18 = input.bool(false, "", group = "Fibonacci Levels", inline = "Level08")
val18 = input.float(3.272, "", group = "Fibonacci Levels", inline = "Level08")
col18 = input.color(#81c784, "", group = "Fibonacci Levels", inline = "Level08")
shw19 = input.bool(false, "", group = "Fibonacci Levels", inline = "Level09")
val19 = input.float(3.414, "", group = "Fibonacci Levels", inline = "Level09")
col19 = input.color(#f44336, "", group = "Fibonacci Levels", inline = "Level09")
shw20 = input.bool(false, "", group = "Fibonacci Levels", inline = "Level09")
val20 = input.float(4.0, "", group = "Fibonacci Levels", inline = "Level09")
col20 = input.color(#81c784, "", group = "Fibonacci Levels", inline = "Level09")
shw21 = input.bool(false, "", group = "Fibonacci Levels", inline = "Level10")
val21 = input.float(4.272, "", group = "Fibonacci Levels", inline = "Level10")
col21 = input.color(#009688, "", group = "Fibonacci Levels", inline = "Level10")
shw22 = input.bool(false, "", group = "Fibonacci Levels", inline = "Level10")
val22 = input.float(4.414, "", group = "Fibonacci Levels", inline = "Level10")
col22 = input.color(#436d87, "", group = "Fibonacci Levels", inline = "Level10")
shw23 = input.bool(false, "", group = "Fibonacci Levels", inline = "Level11")
val23 = input.float(4.618, "", group = "Fibonacci Levels", inline = "Level11")
col23 = input.color(#002396, "", group = "Fibonacci Levels", inline = "Level11")
shw24 = input.bool(false, "", group = "Fibonacci Levels", inline = "Level11")
val24 = input.float(4.764, "", group = "Fibonacci Levels", inline = "Level11")
col24 = input.color(#006696, "", group = "Fibonacci Levels", inline = "Level11")
// |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
// | CALCULATION |
// |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
// ++++++++++++ Supertrend Indicator
[super, dirc] = ta.supertrend(factor, supAtr)
var intlSupr = float(na), var rangSupr = float(na)
intlSupr := dirc != dirc[1] ? super : intlSupr
rangSupr := dirc != dirc[1] ? math.abs(super - super[1]) : rangSupr
// ++++++++++++ Calculate Fib Levels Function
fibLev(x) => intlSupr + (dirc == -1 ? rangSupr : - rangSupr) * x
levFib(x) => (x - intlSupr)/ (dirc == -1 ? rangSupr : - rangSupr)
// ++++++++++++ Entered Fibonacci Levels
var usVal = array.new<float>(na)
var usCol = array.new<color>(na)
usValFun(val, col, flg) =>
if flg
array.push(usVal, val)
array.push(usCol, col)
if barstate.isfirst
usValFun(val01, col01, shw01), usValFun(val02, col02, shw02), usValFun(val03, col03, shw03),
usValFun(val04, col04, shw04), usValFun(val05, col05, shw05), usValFun(val06, col06, shw06),
usValFun(val07, col07, shw07), usValFun(val08, col08, shw08), usValFun(val09, col09, shw09),
usValFun(val10, col10, shw10), usValFun(val11, col11, shw11), usValFun(val12, col12, shw12),
usValFun(val13, col13, shw13), usValFun(val14, col14, shw14), usValFun(val15, col15, shw15),
usValFun(val16, col16, shw16), usValFun(val17, col17, shw17), usValFun(val18, col18, shw18),
usValFun(val19, col19, shw19), usValFun(val20, col20, shw20), usValFun(val21, col21, shw21),
usValFun(val22, col22, shw22), usValFun(val23, col23, shw23), usValFun(val24, col24, shw24),
inVal = array.new<float>(na)
for i = 0 to array.size(usVal) - 1
array.push(inVal, fibLev(array.get(usVal, i)))
array.sort(inVal, dirc < 1 ? order.ascending : order.descending)
// |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
// | DRAWING |
// |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
// ++++++++++++ Get Line Style
styLine(s) =>
switch s
"..........." => line.style_dotted
"-----------" => line.style_dashed
"________" => line.style_solid
// ++++++++++++ Get Line Extention
extLine(l) =>
switch l
"Right Extend" => extend.right
"Left Extend" => extend.left
"Both Extend" => extend.both
=> extend.none
// ++++++++++++ Get Text Label
txtLab(x) =>
prt1 = str.contains(lblSty, "Percent") ? str.tostring(levFib(x) * 100, format.percent) + " ":
str.contains(lblSty, "Value" ) ? str.tostring(levFib(x) , "#.###") + " " : ""
prt2 = str.contains(lblSty, "Price") ? "(" + str.tostring(x, format.mintick) + ")" : ""
(dirc > 0 ? " \n" : "") + prt1 + prt2 + (dirc < 0 ? " \n" : "")
// ++++++++++++ Line Function
linFunc(x1, y, x2, col) =>
line.new(x1, y, x2, y, xloc.bar_index, extLine(linExt), color.new(col, lnTrans), styLine(linSty), linSiz)
// ++++++++++++ Label Function
labFun(y, col) =>
label.new(bar_index, y, txtLab(y), color = color.new(col, 100), size = str.lower(lblSiz),
textcolor = col, style = label.style_label_left, textalign = text.align_left)
// ++++++++++++ Drawing Levels
var runUp = array.new<float>(na) // Collect RunUp Fib
var linArr = array.new<line>(na)
var labArr = array.new<label>(na)
line trnd = na
var trndBr = 0
if array.size(inVal) > 0
if dirc != dirc[1]
if confrim ? barstate.isconfirmed : true
if lastSet
line.delete(trnd[trndBr])
while array.size(linArr) > 0
line.delete(array.shift(linArr))
while array.size(labArr) > 0
label.delete(array.shift(labArr))
else
if array.size(linArr) > 0
for i = 0 to array.size(linArr) - 1
line.set_extend(array.get(linArr, i), extend.none)
if array.size(labArr) > 0
for i = 0 to array.size(labArr) - 1
label.set_style(array.get(labArr, i), label.style_label_right)
array.clear(linArr)
array.clear(labArr)
array.unshift(runUp, levFib(close))
trndBr := 0
for i = 0 to array.size(inVal) - 1
if not na(array.get(inVal, i))
linCol = array.get(usCol, array.indexof(usVal, levFib(array.get(inVal, i))))
// Line
if linExt != "Hide"
array.push(linArr, linFunc(bar_index, array.get(inVal, i), bar_index, linCol))
if array.size(linArr) > 1
linefill.new(array.get(linArr, array.size(linArr)-2),
array.get(linArr, array.size(linArr)-1),
color.new(linCol, bgTrans))
if trndChk and trndBr == 0
trnd := line.new(bar_index, fibLev(1), bar_index, super,
xloc.bar_index, extend.none, trndCol, line.style_dashed, 1)
trndBr := 1
// Label
if lblPos != "Hide"
array.push(labArr, labFun(array.get(inVal, i), linCol))
else
if array.size(runUp) > 0
runUpLast = array.get(runUp, 0)
runUpSrc = dirc == -1 ? high : low
array.set(runUp, 0, runUpLast > levFib(runUpSrc) ? runUpLast : levFib(runUpSrc))
if array.size(linArr) > 0
for i = 0 to array.size(linArr) - 1
line.set_x2(array.get(linArr, i), bar_index)
if array.size(labArr) > 0
for i = 0 to array.size(labArr) - 1
label.set_x(array.get(labArr, i), bar_index)
if trndChk
line.set_x2(trnd[trndBr], bar_index)
trndBr += 1
// Supertrend Plots and Signals
upTrend = plot(pltChk and dirc < 0 ? super : na, "Up Trend", upCol, 3, plot.style_linebr)
downTrend = plot(pltChk and dirc > 0 ? super : na, "Down Trend", dnCol, 3, plot.style_linebr)
plotshape(pltChk and dirc < 0 and dirc != dirc[1] ? super : na, "Long", shape.labelup, location.absolute, upCol, 0, "LONG", color.white, display = display.pane, size = size.small)
plotshape(pltChk and dirc > 0 and dirc != dirc[1] ? super : na, "Short", shape.labeldown, location.absolute, dnCol, 0, "SHORT", color.white, display = display.pane, size = size.small)
// |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
// | STATISTICS |
// |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~[1] Table
// Get Tbale Location & Size
locNsze(x) =>
y = str.split(str.lower(x), " ")
out = ""
for i = 0 to array.size(y) - 1
out := out + array.get(y, i)
if i != array.size(y) - 1
out := out + "_"
out
// Create Table
var tbl = table.new(tablePos != "Hide" ? locNsze(tablePos) : position.top_right, 2, array.size(usVal) + 8,
frame_width = 1, frame_color = color.new(tBgCol, 100), border_width = 1, border_color = color.new(tBgCol, 100))
perFib(x) =>
str.contains(lblSty, "Percent") ? str.tostring(x * 100, format.percent) : str.tostring(x, "#.###")
// Cell Function
cell(col, row, txt, color) =>
table.cell(tbl, col, row, text = txt, text_color = txtCol, bgcolor = color,
text_size = size.small)
// Stats Cells
applyCell(row, des, val) =>
cell(0, row , des, tBgCol), table.merge_cells(tbl, 0, row, 1, row)
cell(0, row +1, val, cBgCol), table.merge_cells(tbl, 0, row +1, 1, row +1)
if barstate.islast and array.size(runUp) > 0 and tablePos != "Hide"
fibVal = array.copy(usVal)
array.sort(fibVal, order.descending)
mtx = matrix.new<float>(array.size(fibVal), 2, 0)
matrix.add_col(mtx, 0, fibVal)
totRunUp = array.size(runUp)
for i = 0 to totRunUp - 1
runup = array.get(runUp, i)
for j = 0 to matrix.rows(mtx) - 1
if not(runup < matrix.get(mtx, j, 0))
matrix.set(mtx, j, 1, matrix.get(mtx, j, 1) + 1)
matrix.set(mtx, j, 2, math.round(matrix.get(mtx, j, 1)/totRunUp * 100, 2))
break
// Table
if array.size(fibVal) > 0
table.clear(tbl, 0, 0, 1, array.size(usVal)+7)
y = 0
cell(0, y, "Historical", tBgCol), table.merge_cells(tbl, 0, 0, 1, 0)
y += 1
cell(0, y, "Fibonacci", tBgCol)
cell(1, y, "RunUP (%)", tBgCol)
y += 1
for i = 0 to matrix.rows(mtx) - 1
fib = matrix.get(mtx, i, 0)
if fib >= 1
Col = array.get(usCol, array.indexof(usVal, fib))
cell(0, y, perFib(fib) , Col)
cell(1, y, str.tostring(matrix.get(mtx, i, 2), format.percent), Col)
y+=1
// Separator
table.cell(tbl, 0, y, height = 2), table.merge_cells(tbl, 0, y, 1, y),
y += 1
applyCell(y, "Number of Trades", str.tostring(array.size(runUp)))
y += 2
applyCell(y, "Median Fib RunUp", perFib(array.median(runUp)))
y += 2
applyCell(y, "Mean Fib RunUp", perFib(array.avg(runUp)))
|
Faytterro Bands | https://www.tradingview.com/script/yXYS7vNg-Faytterro-Bands/ | faytterro | https://www.tradingview.com/u/faytterro/ | 1,151 | 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/
// © faytterro
//@version=5
indicator("Faytterro Bands", overlay=true, max_lines_count=500, max_bars_back = 500)
src=input(hlc3,title="source")
len=input.int(50,title="lenght", maxval=500)
cr(x, y) =>
z = 0.0
weight = 0.0
for i = 0 to y-1
z:=z + x[i]*((y-1)/2+1-math.abs(i-(y-1)/2))
z/(((y+1)/2)*(y+1)/2)
cr= cr(src,2*len-1)
width=2
//plot(cr, color= #cf0202, linewidth=width,offset=-len+1)
dizii = array.new_float(500)
for k=0 to len-1
sum=0.0
for i=0 to 2*len-2-k
sum +=(len-math.abs(len-1-k-i))*src[i]/(len*len-k*(k+1)/2)
array.set(dizii,k, sum )
mult = input.float(2.0, minval=0.001, maxval=50, title="StdDev")
dev = mult * ta.stdev(src, len)
upper = cr + cr(dev, 2*len-1)
lower = cr - cr(dev, 2*len-1)
cu = input.color(color.rgb(255, 137, 137), "upper band color")
cl = input.color(color.rgb(137, 255, 97), "lower band color")
plot(lower, color= cl, offset=1-len, linewidth=2, display = display.pane)
plot(upper, color= cu, offset=1-len, linewidth=2, display = display.pane)
dashed=input.bool(false)
transp=input.bool(true)
d = dashed? 2 : 1
tra=transp? 1 : 0
// extrapolation
diz = array.new_float(500)
var lin=array.new_line()
diz2 = array.new_float(500)
var lin2=array.new_line(0)
if barstate.islast
for k=0 to len-1
sum=0.0
dv=0.0
for i=0 to 2*len-2-k
sum +=(len-math.abs(len-1-k-i))*src[i]/(len*len-k*(k+1)/2)
dv +=(len-math.abs(len-1-k-i))*dev[i]/(len*len-k*(k+1)/2)
array.set(diz,k, sum + dv)
array.set(diz2,k, sum - dv)
for i=0 to (len/d-1)
array.push(lin, line.new(na, na, na, na))
line.set_xy1(array.get(lin,i), bar_index[len]+i*d+1, array.get(diz,i*d))
line.set_xy2(array.get(lin,i), bar_index[len]+i*d+2, array.get(diz,i*d+1))
line.set_color(array.get(lin,i),color.new(cu, tra*i*95/(len/d-1)))//array.get(diz,i*2+1)>=array.get(diz,i*2)? #35cf02 : #cf0202)
line.set_width(array.get(lin,i),width)
array.push(lin2, line.new(na, na, na, na))
line.set_xy1(array.get(lin2,i), bar_index[len]+i*d+1, array.get(diz2,i*d))
line.set_xy2(array.get(lin2,i), bar_index[len]+i*d+2, array.get(diz2,i*d+1))
line.set_color(array.get(lin2,i),color.new(cl, tra*i*95/(len/d-1)) )//array.get(diz2,i*2+1)>=array.get(diz2,i*2)? #35cf02 : #cf0202)
line.set_width(array.get(lin2,i),width)
plot(array.get(diz,len-1), color = color.new(cu,100))
plot(array.get(diz2,len-1), color = color.new(cl,100))
alertcondition(ta.crossover(close,array.get(diz,len-1)) or ta.crossunder(close,array.get(diz2,len-1)), title = "faytterro bands alert",
message = "warning! this is an early warning alert, not a buy or sell signal. Remember that the indicator repaints to a limited extent on the last bars.") |
Dominant Cycle Detection Oscillator | https://www.tradingview.com/script/zeLIeoRG-Dominant-Cycle-Detection-Oscillator/ | BarefootJoey | https://www.tradingview.com/u/BarefootJoey/ | 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/
//
// © BarefootJoey
// ██████████████████████████████████████████████████████████████████████
// █▄─▄─▀██▀▄─██▄─▄▄▀█▄─▄▄─█▄─▄▄─█─▄▄─█─▄▄─█─▄─▄─███▄─▄█─▄▄─█▄─▄▄─█▄─█─▄█
// ██─▄─▀██─▀─███─▄─▄██─▄█▀██─▄███─██─█─██─███─███─▄█─██─██─██─▄█▀██▄─▄██
// █▄▄▄▄██▄▄█▄▄█▄▄█▄▄█▄▄▄▄▄█▄▄▄███▄▄▄▄█▄▄▄▄██▄▄▄██▄▄▄███▄▄▄▄█▄▄▄▄▄██▄▄▄██
//
//@version=5
indicator("Dominant Cycle Detection Oscillator", overlay=false) //, max_bars_back=5000)
import lastguru/DominantCycle/2 as BFJ1 // Thank you and shoutout to @lastguru
// ---------------------------------------- Inputs --------------------------------------------------//
logcheck = input.bool(false, "Has the side scale been changed to Logarithmic?", tooltip="Please change the scale of this indicator's pane to logarithmic for best viewing results. See https://www.tradingview.com/chart/TSLA/9LwmqYq2-How-to-use-log-charts-and-why-they-re-important/ for more information.")
dctype = input.string("MESA MAMA Cycle", "Cycle type ", options=["MESA MAMA Cycle", "Pearson Autocorrelation", "DFT Cycle", "Phase Accumulation"], inline="1",
tooltip ="Generally, the fastest to slowest load times are MAMA (fastest) > Phase Accumulation > DFT > Pearson Autocorrelation (slowest). If you are getting errors, try narrowing the search range for each of the cycle lengths or switching to a faster loading dominant cycle detection algorithm. Pinescript has 20 second load limits for free users and 40 second limits for paid subscribers.")
source = input(close, title=" ", inline="1")
DynamicLowh = input.int(title="Cycle lengths", defval=3, inline="lenh")
DynamicHighh = input.int(title="to", defval=7, inline="lenh")
DynamicLowf = input.int(title="Cycle lengths", defval=8, inline="lenf")
DynamicHighf = input.int(title="to", defval=12, inline="lenf")
DynamicLow2 = input.int(title="Cycle lengths", defval=15, inline="len2")
DynamicHigh2 = input.int(title="to", defval=25, inline="len2")
DynamicLow4 = input.int(title="Cycle lengths", defval=35, inline="len4")
DynamicHigh4 = input.int(title="to", defval=45, inline="len4")
DynamicLow8 = input.int(title="Cycle lengths", defval=75, inline="len8")
DynamicHigh8 = input.int(title="to", defval=85, inline="len8")
DynamicLow16 = input.int(title="Cycle lengths", defval=155, inline="len16")
DynamicHigh16 = input.int(title="to", defval=175, inline="len16")
DynamicLow32 = input.int(title="Cycle lengths", defval=315, inline="len32")
DynamicHigh32 = input.int(title="to", defval=325, inline="len32")
text_size = input.session('Normal', "Text Size", options=["Tiny","Small","Normal","Large"])
dash_loc = input.session("Top Center", "Title Location", options=["Top Right","Bottom Right","Top Left","Bottom Left","Middle Right","Bottom Center", "Top Center"])
title_col = input.color(color.gray, "Title Color")
// ---------------------------------------Calculations -------------------------------------------------//
lengthh = BFJ1.doEstimate(dctype, source, DynamicLowh, DynamicHighh)
lengthf = BFJ1.doEstimate(dctype, source, DynamicLowf, DynamicHighf)
length2 = BFJ1.doEstimate(dctype, source, DynamicLow2, DynamicHigh2)
length4 = BFJ1.doEstimate(dctype, source, DynamicLow4, DynamicHigh4)
length8 = BFJ1.doEstimate(dctype, source, DynamicLow8, DynamicHigh8)
length16 = BFJ1.doEstimate(dctype, source, DynamicLow16, DynamicHigh16)
length32 = BFJ1.doEstimate(dctype, source, DynamicLow32, DynamicHigh32)
// --------------------------------------- Outputs -------------------------------------------------------//
plot(lengthh!=0 ?lengthh:na, "Half Cycle", color=color.purple)
plot(lengthf!=0 ?lengthf:na, "Full Cycle", color=color.blue)
plot(length2!=0 ?length2:na, "2x Cycle", color=color.aqua)
plot(length4!=0 ?length4:na, "4x Cycle", color=color.green)
plot(length8!=0 ?length8:na, "8x Cycle", color=color.yellow)
plot(length16!=0 ?length16:na, "16x Cycle", color=color.orange)
plot(length32!=0 ?length32:na, "32x Cycle", color=color.red)
var label_text_size = text_size == 'Tiny' ? size.tiny :
text_size == 'Small' ? size.small :
text_size == 'Normal' ? size.normal : size.large
var label ch = na
var label cf = na
var label c2 = na
var label c4 = na
var label c8 = na
var label c16 = na
var label c32 = na
if barstate.islast //and logcheck
ch := lengthh!=0?label.new(bar_index, y=lengthh, text=str.tostring(lengthh, '#'), size=label_text_size, style=label.style_label_left, color=color.new(color.white,100), textcolor=color.new(color.purple,0), tooltip="🔄 Cycle: 5 bar/0.5x\n💪 Dominant: " + str.tostring(lengthh, '#') + "\n📡 Search Range: " + str.tostring(DynamicLowh) + " to " + str.tostring(DynamicHighh)) :na
cf := lengthf!=0?label.new(bar_index, y=lengthf, text=str.tostring(lengthf, '#'), size=label_text_size, style=label.style_label_left, color=color.new(color.white,100), textcolor=color.new(color.blue,0), tooltip="🔄 Cycle: 10 bar/1x\n💪 Dominant: " + str.tostring(lengthf, '#') + "\n📡 Search Range: " + str.tostring(DynamicLowf) + " to " + str.tostring(DynamicHighf)) :na
c2 := length2!=0?label.new(bar_index, y=length2, text=str.tostring(length2, '#'), size=label_text_size, style=label.style_label_left, color=color.new(color.white,100), textcolor=color.new(color.aqua,0), tooltip="🔄 Cycle: 20 bar/2x\n💪 Dominant: " + str.tostring(length2, '#') + "\n📡 Search Range: " + str.tostring(DynamicLow2) + " to " + str.tostring(DynamicHigh2)) :na
c4 := length4!=0?label.new(bar_index, y=length4, text=str.tostring(length4, '#'), size=label_text_size, style=label.style_label_left, color=color.new(color.white,100), textcolor=color.new(color.green,0), tooltip="🔄 Cycle: 40 bar/4x\n💪 Dominant: " + str.tostring(length4, '#') + "\n📡 Search Range: " + str.tostring(DynamicLow4) + " to " + str.tostring(DynamicHigh4)) :na
c8 := length8!=0?label.new(bar_index, y=length8, text=str.tostring(length8, '#'), size=label_text_size, style=label.style_label_left, color=color.new(color.white,100), textcolor=color.new(color.yellow,0), tooltip="🔄 Cycle: 80 bar/8x\n💪 Dominant: " + str.tostring(length8, '#') + "\n📡 Search Range: " + str.tostring(DynamicLow8) + " to " + str.tostring(DynamicHigh8)) :na
c16 := length16!=0?label.new(bar_index, y=length16, text=str.tostring(length16, '#'), size=label_text_size, style=label.style_label_left, color=color.new(color.white,100), textcolor=color.new(color.orange,0), tooltip="🔄 Cycle: 160 Bar (20 week)/16x\n💪 Dominant: " + str.tostring(length16, '#') + "\n📡 Search Range: " + str.tostring(DynamicLow16) + " to " + str.tostring(DynamicHigh16)) :na
c32 := length32!=0?label.new(bar_index, y=length32, text=str.tostring(length32, '#'), size=label_text_size, style=label.style_label_left, color=color.new(color.white,100), textcolor=color.new(color.red,0), tooltip="🔄 Cycle: 320 Bar (40 week)/32x\n💪 Dominant: " + str.tostring(length32, '#') + "\n📡 Search Range: " + str.tostring(DynamicLow32) + " to " + str.tostring(DynamicHigh32)) :na
label.delete(ch[1])
label.delete(cf[1])
label.delete(c2[1])
label.delete(c4[1])
label.delete(c8[1])
label.delete(c16[1])
label.delete(c32[1])
var table_position = dash_loc == 'Top Left' ? position.top_left :
dash_loc == 'Bottom Left' ? position.bottom_left :
dash_loc == 'Middle Right' ? position.middle_right :
dash_loc == 'Middle Left' ? position.middle_left :
dash_loc == 'Bottom Center' ? position.bottom_center :
dash_loc == 'Top Center' ? position.top_center :
dash_loc == 'Top Right' ? position.top_right : position.bottom_right
var table dcTypeDisplay = table.new(table_position, 1, 12)
if barstate.islast
table.cell(dcTypeDisplay, 0, 0, text=str.tostring(dctype), text_color=title_col, text_size=label_text_size) //, tooltip="If you dont see the rainbow🌈, please double click here to check/update the settings.")
// EoS made w/ ❤ by @BarefootJoey ✌💗📈 |
Gamification Indicator | https://www.tradingview.com/script/GdO8hbRE-Gamification-Indicator/ | BarefootJoey | https://www.tradingview.com/u/BarefootJoey/ | 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/
// © BarefootJoey
// ██████████████████████████████████████████████████████████████████████
// █▄─▄─▀██▀▄─██▄─▄▄▀█▄─▄▄─█▄─▄▄─█─▄▄─█─▄▄─█─▄─▄─███▄─▄█─▄▄─█▄─▄▄─█▄─█─▄█
// ██─▄─▀██─▀─███─▄─▄██─▄█▀██─▄███─██─█─██─███─███─▄█─██─██─██─▄█▀██▄─▄██
// █▄▄▄▄██▄▄█▄▄█▄▄█▄▄█▄▄▄▄▄█▄▄▄███▄▄▄▄█▄▄▄▄██▄▄▄██▄▄▄███▄▄▄▄█▄▄▄▄▄██▄▄▄██
//@version=5
indicator(title="Gamification Indicator", overlay=true)
// -------------------------------- Groups ---------------------------------- //
grp = "Player"
grt = "Trend"
gro = "Obstacle"
grc = "Celestial"
// --------------------------------- Colors --------------------------------- //
red = color.red
green = color.green
nocol = color.gray
brightred = #ff1100
brightgreen = #00ff0a
// -------------------------------- Theme ----------------------------------- //
// Additional Emoji COnsiderations
// Celestial/Top🌙🌜⛳
// Obstacles🌳🪁🚧
surfer =" 🏄♂️"
merman = "🧜♂"
skier = "🏂"
alien = "🛸"
plane = "🛫"
parachute = "🪂"
rocket = "🚀"
butterfly = "🦋"
pacishman = "👾"
shark = "🦈"
earth = "🌎"
tree = "🌲"
mountain ="🗻"
cactus = "🌵"
fire = "🔥"
waves = "🌊"
volcano = "🌋"
lightning = "⚡"
sun = "🌞"
moon = "🌛"
galaxy = "🌌"
saturn = "🪐"
error = "⛔"
// -------------------------------- Constants ------------------------------- //
constantvar=1>0
// Decimals
pricedecimals= input.int(defval=2, title='Number of Price Decimals', minval=0, maxval=10)
truncateprice(number, pricedecimals) =>
factor = math.pow(10, pricedecimals)
int(number * factor) / factor
// --------------------------------- Inputs --------------------------------- //
size = input.string(size.huge, "Emoji Size", [size.tiny, size.small, size.normal, size.large, size.huge])
transp = input.int(20, "Emoji Transparency", minval=0, maxval=100)
vehicle = input.string(plane, "Player Emoji", options=[plane,alien,parachute,rocket,butterfly,merman,surfer,"Custom","None"], group=grp)
customv = input.string("👾", "Custom Player Emoji", group=grp)
trend = input.string("Clouds", "Trend Type", options=["Clouds", "Waves", "Channel", "None"],group=grt)
// ------------------------- Ichimoku Clouds -------------------------------- //
// Inputs
conversionPeriods = 9
basePeriods = 26
laggingSpan2Periods = 52
displacement = 26
//
// Calculations
donchian(len) => math.avg(ta.lowest(len), ta.highest(len))
conversionLine = donchian(conversionPeriods)
baseLine = donchian(basePeriods)
leadLine1 = math.avg(conversionLine, baseLine)
leadLine2 = donchian(laggingSpan2Periods)
// Plots & Fills
p3 = plot(conversionLine, color=nocol, title="Conversion Line (Tenkan-Sen)", display=display.none, editable=false)
p4 = plot(baseLine, color=conversionLine>baseLine?green:red, title="Base Line (Kijun-sen)", display=display.none, editable=false)
fill(p3, p4, color = trend == "Clouds" ? color.new(nocol,80):na)
p1 = plot(leadLine1, offset = displacement - 1, color=nocol, title="Leading Span A (Senkou Span A)", display=display.none, editable=false) // green
p2 = plot(leadLine2, offset = displacement - 1, color=leadLine1>leadLine2?green:red, title="Leading Span B (Senkou Span B)", display=display.none, editable=false) // green
fill(p1, p2, color = trend == "Clouds" ? color.new(nocol,80):na)
// ----------------------------------- MA Clouds ---------------------------- //
fastma1 =ta.ema(close,8)
fastma2 =ta.ema(close,34)
slowma1 =ta.ema(close,89)
slowma2 =ta.ema(close,233)
slowestma = ta.ema(close,618)
fastma1f = plot(fastma1, color=color.gray, display=display.none, editable=false)
fastma2f = plot(fastma2, color=color.gray, display=display.none, editable=false)
slowma1f = plot(slowma1, color=color.gray, display=display.none, editable=false)
slowma2f = plot(slowma2, color=color.gray, display=display.none, editable=false)
slowest = plot(slowestma, color=color.gray, display=display.none, editable=false)
fill(fastma1f, fastma2f, color=trend == "Waves" ? color.new(color.blue,80):na)
fill(fastma2f, slowma1f, color=trend == "Waves" ? color.new(color.blue,90):na)
fill(slowma1f, slowma2f, color=trend == "Waves" ? color.new(color.blue,95):na)
fill(fastma1f, slowest, color=trend == "Waves" ? color.new(color.blue,80):na)
// ------------------------------------ Channel ----------------------------- //
length = 233 //input(233, 'Channel Length', group = grt)
highestBar = ta.highest(high, length)
lowestBar = ta.lowest(low, length)
midBar = (highestBar + lowestBar) / 2
channelColor = color.new(#964b00,65)
midChannel = plot(trend == "Channel" ? midBar : na, color=channelColor, style=plot.style_line, linewidth=1)
upperChannel = plot(trend == "Channel" ? highestBar : na, color=channelColor, style=plot.style_line, linewidth=1)
lowerChannel = plot(trend == "Channel" ? lowestBar : na, color=channelColor, style=plot.style_line, linewidth=1)
upperMidChannel = plot(trend == "Channel" ? midBar + (highestBar - midBar) * 0.5 : na, style=plot.style_line, linewidth=1, color=channelColor, display=display.none)
lowerMidChannel = plot(trend == "Channel" ? midBar - (midBar - lowestBar) * 0.5 : na, style=plot.style_line, linewidth=1, color=channelColor, display=display.none)
fill(midChannel, upperChannel, color=trend == "Channel" ? color.new(#964b00, 95) : na)
fill(lowerChannel, midChannel, color=trend == "Channel" ? color.new(#964b00, 95) : na)
fill(upperMidChannel, upperChannel, color=trend == "Channel" ? color.new(#964b00, 80) : na)
fill(lowerChannel, lowerMidChannel, color=trend == "Channel" ? color.new(#964b00, 80) : na)
// ------------------------------ Player ------------------------------------ //
// ConTrail (OHLC4)
src = input.source(ohlc4, "Source", group=grp)
ctlen = input.int(89, "Trail Color Fade Length", minval=1, group=grp)
ctcol = input.color(color.white, "Trail Color", group=grp)
plot(src, "OHLC4 Long Trail", color=color.new(ctcol,80), linewidth=3)
plot(src, "OHLC4 Mid Trail", color=color.new(ctcol,65), linewidth=2, show_last=ctlen*3)
plot(src, "OHLC4 Short Trail", color=color.new(ctcol,50), linewidth=1, show_last=ctlen)
// Current Altitude (Price Line)
linelevel=src
altcol = src>src[1] ? green: red
var line l8 = na
line.delete(l8)
l8 := line.new(bar_index, linelevel, bar_index + 25, linelevel, color=color.new(altcol, 0), style=line.style_dotted)
// Altitude Label (Price Label)
altoffset = input.int(7, "Price Close Label Horizontal Offset", group=grp)
var label bl = na
label.delete(bl)
bl := label.new(bar_index + altoffset, linelevel, str.tostring(truncateprice(close, pricedecimals)), textcolor=altcol, color=color.new(#000000, 100), style=label.style_label_down, size=size.small)
// Vehicle Label
emoji2 = src>src[1]?"🛫":"🛬"
whichvehicle=vehicle == plane ? emoji2 : vehicle == alien ? alien : vehicle == parachute ? parachute : vehicle == "Custom" ? customv : vehicle == "None" ? na : vehicle == merman ? merman : vehicle == rocket ? rocket : vehicle == butterfly ? butterfly : vehicle == surfer ? surfer : error
col = color.orange
planelocation = yloc.price
planePrice = ta.valuewhen(bar_index, src, 0)
var label planel = na
planel := label.new(bar_index, y=planePrice, yloc=planelocation, size=size, text=whichvehicle, style=label.style_none, textcolor=color.new(col,transp))
label.delete(planel[1])
// ------------------------------ Celestial --------------------------------- //
// Define Daytime, get corresponding Sun/Moon emoji, and give tooltips
zero = timestamp(2009, 03, 11, 00, 00)
ts = time('D')
lunarmonth = 2551442890
altcols = 4
rot = (ts - zero) / (lunarmonth/8) % 8
daytime = time(timeframe.period, '0700-1900')
whichmoon = rot<1 ? "🌕" : rot<2 ? "🌔" : rot<3 ? "🌓" : rot<4 ? "🌒" : rot<5 ? "🌑" : rot<6 ? "🌒" : rot<7 ? "🌗" : rot<8 ? "🌖" : na
ttip = rot<1 ? "Full Moon (4/8)" : rot<2 ? "Waning Gibbous (5/8)" : rot<3 ? "Last Quarter (6/8)" : rot<4 ? "Waning Crescent (7/8)" : rot<5 ? "New/No Moon (8/8)" : rot<6 ? "Waxing Crescent (1/8)" : rot<7 ? "First Quarter (2/8)" : rot<8 ? "Waxing Gibbous (3/8)" : na
watermark2 = daytime ? '🌞' : whichmoon
actualtt = "🌙 Phase: " + ttip
// Plot the celestial body
watermark4 = input.string("Live/Actual", "Celestial Emoji", options=[lightning, sun, moon, galaxy, saturn, "Live/Actual","Custom", "None"],group=grc)
customc = input.string("🌙", "Custom Celestial Emoji", group=grc)
whichcelestial = watermark4 == moon ? moon : watermark4 == lightning ? lightning : watermark4 == sun ? sun : watermark4 == galaxy ? galaxy : watermark4 == saturn ? saturn : watermark4 == "Live/Actual" ? watermark2 : watermark4 == "None" ? na : watermark4 == "Custom" ? customc : error
whichcelestialtt = watermark4 == "Live/Actual" ? actualtt : na
position4 = position.top_right
var table celestial = table.new(position4, 1, 1)
table.cell(celestial, 0, 0, whichcelestial, text_size = size, text_color = color.new(col, transp), tooltip=whichcelestialtt)
// --------------------------------- Obstacle ------------------------------- //
watermark3 = input.string(mountain, "Obstacle Emoji", options=[mountain, shark, tree, earth, fire, volcano, waves, "Custom", "None"],group=gro)
customo = input.string(cactus, "Custom Obstacle Emoji", group=gro)
whichobstacle = watermark3 == mountain ? mountain : watermark3 == shark ? shark : watermark3 == tree ? tree : watermark3 == earth ? earth : watermark3 ==fire ? fire : watermark3 == volcano ? volcano : watermark3 == "Custom" ? customo : watermark3 == "None" ? na : watermark3== waves ? waves : error
position3 = position.bottom_right
var table obstacle = table.new(position3, 1, 1)
table.cell(obstacle, 0, 0, whichobstacle, text_size = size, text_color = color.new(col, transp))
// EoS made w/ ❤ by @BarefootJoey ✌💗📈 |
The Perfect Support & Resistance | https://www.tradingview.com/script/YO6BLV9V-The-Perfect-Support-Resistance/ | Yidu_A_S_O_T_L_J_C | https://www.tradingview.com/u/Yidu_A_S_O_T_L_J_C/ | 349 | 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/
// © Yidu_A_S_O_T_L_J_C
//@version=5
indicator("The Perfect Support & Resistance", "The Perfect S&R", overlay = true)
// Identify structure and lookback points to the left
// 10 levels max required
// assign each level one after another. -- rsi > 70 -> resistance and rsi < 30 -> support
rsiG = "RSI Settings"
rsiLengthInput = input.int(14, minval=1, title="RSI Length", group=rsiG)
rsiSourceInput = input.source(close, "Source", group=rsiG)
overbought = input.int(70, minval=50, maxval = 100, title="Overbought Threshold", group=rsiG)
oversold = input.int(30, minval=0, maxval = 50, title="Oversold Threshold", group=rsiG)
lbG = "Lookback"
lookback_0 = input.int(200, "Lookback zone 1", group = lbG)
lookback_1 = input.int(100, "Lookback zone 2", group = lbG)
lookback_2 = input.int(50, "Lookback zone 3", group = lbG)
lookback_3 = input.int(20, "Lookback zone 4", group = lbG)
lookback_4 = input.int(10, "Lookback zone 5", group = lbG)
tfG = "HTF"
htf = input.timeframe("5", "Timeframe1", group=tfG)
htf2 = input.timeframe("30", "Timeframe2", group=tfG)
up = ta.rma(math.max(ta.change(rsiSourceInput), 0), rsiLengthInput)
down = ta.rma(-math.min(ta.change(rsiSourceInput), 0), rsiLengthInput)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))
var float level0High_tf = na
var float level0Low_tf = na
var float level1High_tf = na
var float level1Low_tf = na
var float level2High_tf = na
var float level2Low_tf = na
var float level3High_tf = na
var float level3Low_tf = na
var float level4High_tf = na
var float level4Low_tf = na
var float level0High = na
var float level0Low = na
var float level1High = na
var float level1Low = na
var float level2High = na
var float level2Low = na
var float level3High = na
var float level3Low = na
var float level4High = na
var float level4Low = na
swings(int len) =>
var int os = 0
var float itop = na
var float ibtm = na
upper = ta.highest(rsi, len)
lower = ta.lowest(rsi, len)
os := rsi[len] > upper and rsi[len] > overbought ? 0 : rsi[len] < lower and rsi[len] < oversold ? 1 : os[1]
if (os == 0 and os[1] != 0)
itop := high[len]
if (os == 1 and os[1] != 1)
ibtm := low[len]
[itop, ibtm]
[level0_high, level0_low] = request.security(syminfo.tickerid, htf, swings(lookback_0))
[level1_high, level1_low] = request.security(syminfo.tickerid, htf, swings(lookback_1))
[level2_high, level2_low] = request.security(syminfo.tickerid, htf, swings(lookback_2))
[level3_high, level3_low] = request.security(syminfo.tickerid, htf, swings(lookback_3))
[level4_high, level4_low] = request.security(syminfo.tickerid, htf, swings(lookback_4))
// HTF
[level0_high_tf, level0_low_tf] = request.security(syminfo.tickerid, htf2, swings(lookback_0))
[level1_high_tf, level1_low_tf] = request.security(syminfo.tickerid, htf2, swings(lookback_1))
[level2_high_tf, level2_low_tf] = request.security(syminfo.tickerid, htf2, swings(lookback_2))
[level3_high_tf, level3_low_tf] = request.security(syminfo.tickerid, htf2, swings(lookback_3))
[level4_high_tf, level4_low_tf] = request.security(syminfo.tickerid, htf2, swings(lookback_4))
plot(level0_high, "Level 0 Resistance", close > level0_high ? color.lime : color.rgb(255, 166, 0), style = plot.style_circles)
plot(level1_high, "Level 1 Resistance", close > level1_high ? color.lime : color.rgb(255, 166, 0), style = plot.style_circles)
plot(level2_high, "Level 2 Resistance", close > level2_high ? color.lime : color.rgb(255, 166, 0), style = plot.style_circles)
plot(level3_high, "Level 3 Resistance", close > level3_high ? color.lime : color.rgb(255, 166, 0), style = plot.style_circles)
plot(level4_high, "Level 4 Resistance", close > level4_high ? color.lime : color.rgb(255, 166, 0), style = plot.style_circles)
plot(level0_high_tf, "Level 0 Resistance TF", color.white, style = plot.style_circles)
plot(level1_high_tf, "Level 1 Resistance TF", color.white, style = plot.style_circles)
plot(level2_high_tf, "Level 2 Resistance TF", color.white, style = plot.style_circles)
plot(level3_high_tf, "Level 3 Resistance TF", color.white, style = plot.style_circles)
plot(level4_high_tf, "Level 4 Resistance TF", color.white, style = plot.style_circles)
plot(level0_low, "Level 0 Support", close > level0_low ? color.lime : color.rgb(255, 166, 0), style = plot.style_circles)
plot(level1_low, "Level 1 Support", close > level1_low ? color.lime : color.rgb(255, 166, 0), style = plot.style_circles)
plot(level2_low, "Level 2 Support", close > level2_low ? color.lime : color.rgb(255, 166, 0), style = plot.style_circles)
plot(level3_low, "Level 3 Support", close > level3_low ? color.lime : color.rgb(255, 166, 0), style = plot.style_circles)
plot(level4_low, "Level 4 Support", close > level4_low ? color.lime : color.rgb(255, 166, 0), style = plot.style_circles)
plot(level0_low_tf, "Level 0 Support TF", color.white, style = plot.style_circles)
plot(level1_low_tf, "Level 1 Support TF", color.white, style = plot.style_circles)
plot(level2_low_tf, "Level 2 Support TF", color.white, style = plot.style_circles)
plot(level3_low_tf, "Level 3 Support TF", color.white, style = plot.style_circles)
plot(level4_low_tf, "Level 4 Support TF", color.white, style = plot.style_circles) |
TICK - Custom Tickers [Pt] | https://www.tradingview.com/script/RW3rErWa-TICK-Custom-Tickers-Pt/ | PtGambler | https://www.tradingview.com/u/PtGambler/ | 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/
// © PtGambler
//@version=5
indicator("TICK - Custom Tickers [Pt]", shorttitle = 'TICK-Custom[Pt]', timeframe = '', timeframe_gaps = false)
group1 = 'Symbols'
group2 = 'Top 20'
group3 = 'Top 30'
group4 = 'Top 40'
t1 = time(timeframe.period, "0930-1600:23456", 'America/New_York')
mode = input.string("Bar", 'Display Mode', ['Bar', 'Line', 'Both', 'Cumulative'])
apply_ma = input.bool(true, '└ Apply SMA', inline = 'ma')
ma_len = input.int(3, '', inline = 'ma', tooltip = 'Only applies to Line or Cumulative plots')
sym_count = input.string('Top 10', 'Number of Tickers', ['Top 7','Top 10', 'Top 20', 'Top 30', 'Top 40'])
symbol1 = input.symbol(defval = "AAPL", group = group1)
symbol2 = input.symbol(defval = "MSFT", group = group1)
symbol3 = input.symbol(defval = "AMZN", group = group1)
symbol4 = input.symbol(defval = "TSLA", group = group1)
symbol5 = input.symbol(defval = "GOOGL", group = group1)
symbol6 = input.symbol(defval = "BRK.B", group = group1)
symbol7 = input.symbol(defval = "UNH", group = group1)
symbol8 = input.symbol(defval = "XOM", group = group1)
symbol9 = input.symbol(defval = "JNJ", group = group1)
symbol10 = input.symbol(defval = "NVDA", group = group1)
symbol11 = input.symbol(defval = "JNJ", group = group2)
symbol12 = input.symbol(defval = "HD", group = group2)
symbol13 = input.symbol(defval = "PG", group = group2)
symbol14 = input.symbol(defval = "V", group = group2)
symbol15 = input.symbol(defval = "PFE", group = group2)
symbol16 = input.symbol(defval = "BAC", group = group2)
symbol17 = input.symbol(defval = "MA", group = group2)
symbol18 = input.symbol(defval = "ADBE", group = group2)
symbol19 = input.symbol(defval = "DIS", group = group2)
symbol20 = input.symbol(defval = "NFLX", group = group2)
symbol21 = input.symbol(defval = "TMO", group = group3)
symbol22 = input.symbol(defval = "XOM", group = group3)
symbol23 = input.symbol(defval = "CRM", group = group3)
symbol24 = input.symbol(defval = "CSCO", group = group3)
symbol25 = input.symbol(defval = "COST", group = group3)
symbol26 = input.symbol(defval = "ABT", group = group3)
symbol27 = input.symbol(defval = "PEP", group = group3)
symbol28 = input.symbol(defval = "ABBV", group = group3)
symbol29 = input.symbol(defval = "KO", group = group3)
symbol30 = input.symbol(defval = "PYPL", group = group3)
symbol31 = input.symbol(defval = "CVX", group = group4)
symbol32 = input.symbol(defval = "CMCSA", group = group4)
symbol33 = input.symbol(defval = "LLY", group = group4)
symbol34 = input.symbol(defval = "QCOM", group = group4)
symbol35 = input.symbol(defval = "NKE", group = group4)
symbol36 = input.symbol(defval = "VZ", group = group4)
symbol37 = input.symbol(defval = "WMT", group = group4)
symbol38 = input.symbol(defval = "INTC", group = group4)
symbol39 = input.symbol(defval = "ACN", group = group4)
symbol40 = input.symbol(defval = "AVGO", group = group4)
count = switch sym_count
'Top 7' => 7
'Top 10' => 10
'Top 20' => 20
'Top 30' => 30
'Top 40' => 40
ticks = array.new_int(count, 0)
f_getTick(_sym, _index) =>
tick = request.security(_sym, timeframe.period, close > open ? 1 : close < open ? -1 : 0)
array.set(ticks, _index, tick)
f_getTick(symbol1, 0)
f_getTick(symbol2, 1)
f_getTick(symbol3, 2)
f_getTick(symbol4, 3)
f_getTick(symbol5, 4)
f_getTick(symbol6, 5)
f_getTick(symbol7, 6)
if count > 7
f_getTick(symbol8, 7)
f_getTick(symbol9, 8)
f_getTick(symbol10, 9)
if count > 10
f_getTick(symbol11, 10)
f_getTick(symbol12, 11)
f_getTick(symbol13, 12)
f_getTick(symbol14, 13)
f_getTick(symbol15, 14)
f_getTick(symbol16, 15)
f_getTick(symbol17, 16)
f_getTick(symbol18, 17)
f_getTick(symbol19, 18)
f_getTick(symbol20, 19)
if count > 20
f_getTick(symbol21, 20)
f_getTick(symbol22, 21)
f_getTick(symbol23, 22)
f_getTick(symbol24, 23)
f_getTick(symbol25, 24)
f_getTick(symbol26, 25)
f_getTick(symbol27, 26)
f_getTick(symbol28, 27)
f_getTick(symbol29, 28)
f_getTick(symbol30, 29)
if count > 30
f_getTick(symbol31, 30)
f_getTick(symbol32, 31)
f_getTick(symbol33, 32)
f_getTick(symbol34, 33)
f_getTick(symbol35, 34)
f_getTick(symbol36, 35)
f_getTick(symbol37, 36)
f_getTick(symbol38, 37)
f_getTick(symbol39, 38)
f_getTick(symbol40, 39)
tickC = array.sum(ticks)
tickO = nz(tickC[1])
tickH = math.max(tickO, tickC)
tickL = math.min(tickO, tickC)
tickC_line = tickC * 1.
// Cumulative TICK ----------------------------------
var ctick = 0.0
ctick_ma = 0.0
if t1 and not session.isfirstbar_regular
ctick += tickC
else if session.isfirstbar_regular
ctick := tickC
ma_len := apply_ma ? math.min(ta.barssince(session.isfirstbar_regular)+1, ma_len) : 1
ctick_ma := ta.sma(ctick, ma_len)
tickC_line := ta.sma(tickC, ma_len)
plotcandle(t1 and (mode == 'Bar' or mode == 'Both') ? tickO : na, tickH, tickL, tickC, "TICK", color = tickC > tickO ? color.lime : color.red, wickcolor = tickC > tickO ? color.lime : color.red, bordercolor = tickC > tickO ? color.lime : color.red)
plot(t1 and (mode == 'Line' or mode == 'Both') ? tickC_line : na, color = color.yellow, linewidth = 2, style = plot.style_linebr)
plot(t1 and mode == 'Cumulative' ? ctick_ma : na, "Cumulative TICK", ctick_ma > 0 and ctick_ma < ctick_ma[1] ? color.new(color.green,80) : ctick_ma > 0 and ctick_ma >= ctick_ma[1] ? color.new(color.green,50) : ctick_ma < 0 and ctick_ma < ctick_ma[1] ? color.new(color.red, 50) : color.new(color.red, 80), style = plot.style_columns)
hline(count, 'Top line', mode != 'Cumulative' ? color.gray : color.new(color.black, 100))
hline(0, 'Zero line', color.white)
hline(-count, 'Bottom line', mode != 'Cumulative' ? color.gray : color.new(color.black, 100)) |
Subsets and Splits